blob: 59edc7902dd321bcc8367ad7cccd155083a636a8 [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
QUICHE teama6ef0a62019-03-07 20:34:33 -050053// Number of bits the packet number length bits are shifted from the right
54// edge of the header.
55const uint8_t kPublicHeaderSequenceNumberShift = 4;
56
57// There are two interpretations for the Frame Type byte in the QUIC protocol,
58// resulting in two Frame Types: Special Frame Types and Regular Frame Types.
59//
60// Regular Frame Types use the Frame Type byte simply. Currently defined
61// Regular Frame Types are:
62// Padding : 0b 00000000 (0x00)
63// ResetStream : 0b 00000001 (0x01)
64// ConnectionClose : 0b 00000010 (0x02)
65// GoAway : 0b 00000011 (0x03)
66// WindowUpdate : 0b 00000100 (0x04)
67// Blocked : 0b 00000101 (0x05)
68//
69// Special Frame Types encode both a Frame Type and corresponding flags
70// all in the Frame Type byte. Currently defined Special Frame Types
71// are:
72// Stream : 0b 1xxxxxxx
73// Ack : 0b 01xxxxxx
74//
75// Semantics of the flag bits above (the x bits) depends on the frame type.
76
77// Masks to determine if the frame type is a special use
78// and for specific special frame types.
79const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000
80const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000
81const uint8_t kQuicFrameTypeStreamMask = 0x80;
82const uint8_t kQuicFrameTypeAckMask = 0x40;
83static_assert(kQuicFrameTypeSpecialMask ==
84 (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask),
85 "Invalid kQuicFrameTypeSpecialMask");
86
87// The stream type format is 1FDOOOSS, where
88// F is the fin bit.
89// D is the data length bit (0 or 2 bytes).
90// OO/OOO are the size of the offset.
91// SS is the size of the stream ID.
92// Note that the stream encoding can not be determined by inspection. It can
93// be determined only by knowing the QUIC Version.
94// Stream frame relative shifts and masks for interpreting the stream flags.
95// StreamID may be 1, 2, 3, or 4 bytes.
96const uint8_t kQuicStreamIdShift = 2;
97const uint8_t kQuicStreamIDLengthMask = 0x03;
98
99// Offset may be 0, 2, 4, or 8 bytes.
100const uint8_t kQuicStreamShift = 3;
101const uint8_t kQuicStreamOffsetMask = 0x07;
102
103// Data length may be 0 or 2 bytes.
104const uint8_t kQuicStreamDataLengthShift = 1;
105const uint8_t kQuicStreamDataLengthMask = 0x01;
106
107// Fin bit may be set or not.
108const uint8_t kQuicStreamFinShift = 1;
109const uint8_t kQuicStreamFinMask = 0x01;
110
111// The format is 01M0LLOO, where
112// M if set, there are multiple ack blocks in the frame.
113// LL is the size of the largest ack field.
114// OO is the size of the ack blocks offset field.
115// packet number size shift used in AckFrames.
116const uint8_t kQuicSequenceNumberLengthNumBits = 2;
117const uint8_t kActBlockLengthOffset = 0;
118const uint8_t kLargestAckedOffset = 2;
119
120// Acks may have only one ack block.
121const uint8_t kQuicHasMultipleAckBlocksOffset = 5;
122
123// Timestamps are 4 bytes followed by 2 bytes.
124const uint8_t kQuicNumTimestampsLength = 1;
125const uint8_t kQuicFirstTimestampLength = 4;
126const uint8_t kQuicTimestampLength = 2;
127// Gaps between packet numbers are 1 byte.
128const uint8_t kQuicTimestampPacketNumberGapLength = 1;
129
130// Maximum length of encoded error strings.
131const int kMaxErrorStringLength = 256;
132
133const uint8_t kConnectionIdLengthAdjustment = 3;
134const uint8_t kDestinationConnectionIdLengthMask = 0xF0;
135const uint8_t kSourceConnectionIdLengthMask = 0x0F;
136
137// Returns the absolute value of the difference between |a| and |b|.
138uint64_t Delta(uint64_t a, uint64_t b) {
139 // Since these are unsigned numbers, we can't just return abs(a - b)
140 if (a < b) {
141 return b - a;
142 }
143 return a - b;
144}
145
146uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) {
147 return (Delta(target, a) < Delta(target, b)) ? a : b;
148}
149
150uint64_t PacketNumberIntervalLength(
151 const QuicInterval<QuicPacketNumber>& interval) {
152 if (interval.Empty()) {
153 return 0u;
154 }
155 return interval.max() - interval.min();
156}
157
158QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) {
159 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
160 case PACKET_FLAGS_8BYTE_PACKET:
161 return PACKET_6BYTE_PACKET_NUMBER;
162 case PACKET_FLAGS_4BYTE_PACKET:
163 return PACKET_4BYTE_PACKET_NUMBER;
164 case PACKET_FLAGS_2BYTE_PACKET:
165 return PACKET_2BYTE_PACKET_NUMBER;
166 case PACKET_FLAGS_1BYTE_PACKET:
167 return PACKET_1BYTE_PACKET_NUMBER;
168 default:
169 QUIC_BUG << "Unreachable case statement.";
170 return PACKET_6BYTE_PACKET_NUMBER;
171 }
172}
173
dschinazi17d42422019-06-18 16:35:07 -0700174QuicPacketNumberLength ReadAckPacketNumberLength(
175 QuicTransportVersion /*version*/,
176 uint8_t flags) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500177 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
178 case PACKET_FLAGS_8BYTE_PACKET:
179 return PACKET_6BYTE_PACKET_NUMBER;
180 case PACKET_FLAGS_4BYTE_PACKET:
181 return PACKET_4BYTE_PACKET_NUMBER;
182 case PACKET_FLAGS_2BYTE_PACKET:
183 return PACKET_2BYTE_PACKET_NUMBER;
184 case PACKET_FLAGS_1BYTE_PACKET:
185 return PACKET_1BYTE_PACKET_NUMBER;
186 default:
187 QUIC_BUG << "Unreachable case statement.";
188 return PACKET_6BYTE_PACKET_NUMBER;
189 }
190}
191
192uint8_t PacketNumberLengthToOnWireValue(
fayangf36e29d2019-06-06 14:03:40 -0700193 QuicTransportVersion version,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500194 QuicPacketNumberLength packet_number_length) {
fayangf36e29d2019-06-06 14:03:40 -0700195 if (version > QUIC_VERSION_44) {
196 return packet_number_length - 1;
197 }
198 switch (packet_number_length) {
199 case PACKET_1BYTE_PACKET_NUMBER:
200 return 0;
201 case PACKET_2BYTE_PACKET_NUMBER:
202 return 1;
203 case PACKET_4BYTE_PACKET_NUMBER:
204 return 2;
205 default:
206 QUIC_BUG << "Invalid packet number length.";
207 return 0;
208 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500209}
210
211bool GetShortHeaderPacketNumberLength(
212 QuicTransportVersion version,
213 uint8_t type,
214 bool infer_packet_header_type_from_version,
215 QuicPacketNumberLength* packet_number_length) {
216 DCHECK(!(type & FLAGS_LONG_HEADER));
217 const bool two_bits_packet_number_length =
fayangf36e29d2019-06-06 14:03:40 -0700218 infer_packet_header_type_from_version ? version > QUIC_VERSION_44
QUICHE teama6ef0a62019-03-07 20:34:33 -0500219 : (type & FLAGS_FIXED_BIT);
220 if (two_bits_packet_number_length) {
221 *packet_number_length =
222 static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
223 return true;
224 }
225 switch (type & 0x07) {
226 case 0:
227 *packet_number_length = PACKET_1BYTE_PACKET_NUMBER;
228 break;
229 case 1:
230 *packet_number_length = PACKET_2BYTE_PACKET_NUMBER;
231 break;
232 case 2:
233 *packet_number_length = PACKET_4BYTE_PACKET_NUMBER;
234 break;
235 default:
236 *packet_number_length = PACKET_6BYTE_PACKET_NUMBER;
237 return false;
238 }
239 return true;
240}
241
fayangf36e29d2019-06-06 14:03:40 -0700242uint8_t LongHeaderTypeToOnWireValue(QuicTransportVersion version,
243 QuicLongHeaderType type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500244 switch (type) {
245 case INITIAL:
fayangf36e29d2019-06-06 14:03:40 -0700246 return version > QUIC_VERSION_44 ? 0 : 0x7F;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500247 case ZERO_RTT_PROTECTED:
fayangf36e29d2019-06-06 14:03:40 -0700248 return version > QUIC_VERSION_44 ? 1 << 4 : 0x7C;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500249 case HANDSHAKE:
fayangf36e29d2019-06-06 14:03:40 -0700250 return version > QUIC_VERSION_44 ? 2 << 4 : 0x7D;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500251 case RETRY:
fayangf36e29d2019-06-06 14:03:40 -0700252 return version > QUIC_VERSION_44 ? 3 << 4 : 0x7E;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500253 case VERSION_NEGOTIATION:
254 return 0xF0; // Value does not matter
255 default:
256 QUIC_BUG << "Invalid long header type: " << type;
257 return 0xFF;
258 }
259}
260
261bool GetLongHeaderType(QuicTransportVersion version,
262 uint8_t type,
263 QuicLongHeaderType* long_header_type) {
264 DCHECK((type & FLAGS_LONG_HEADER) && version != QUIC_VERSION_UNSUPPORTED);
fayangf36e29d2019-06-06 14:03:40 -0700265 if (version > QUIC_VERSION_44) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500266 switch ((type & 0x30) >> 4) {
267 case 0:
268 *long_header_type = INITIAL;
269 break;
270 case 1:
271 *long_header_type = ZERO_RTT_PROTECTED;
272 break;
273 case 2:
274 *long_header_type = HANDSHAKE;
275 break;
276 case 3:
277 *long_header_type = RETRY;
278 break;
279 default:
280 QUIC_BUG << "Unreachable statement";
dschinazi072da7c2019-05-07 17:57:42 -0700281 *long_header_type = INVALID_PACKET_TYPE;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500282 return false;
283 }
284 return true;
285 }
286
287 switch (type & 0x7F) {
288 case 0x7F:
289 *long_header_type = INITIAL;
290 break;
291 case 0x7C:
292 *long_header_type = ZERO_RTT_PROTECTED;
293 break;
294 case 0x7D:
295 *long_header_type = HANDSHAKE;
296 break;
297 case 0x7E:
298 *long_header_type = RETRY;
299 break;
300 default:
301 // Invalid packet header type. Whether a packet is version negotiation is
302 // determined by the version field.
303 *long_header_type = INVALID_PACKET_TYPE;
304 return false;
305 }
306 return true;
307}
308
309QuicPacketNumberLength GetLongHeaderPacketNumberLength(
310 QuicTransportVersion version,
311 uint8_t type) {
fayangf36e29d2019-06-06 14:03:40 -0700312 if (version > QUIC_VERSION_44) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500313 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
314 }
315 return PACKET_4BYTE_PACKET_NUMBER;
316}
317
QUICHE team10b22a12019-03-21 15:31:42 -0700318// Used to get packet number space before packet gets decrypted.
319PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
320 switch (header.form) {
321 case GOOGLE_QUIC_PACKET:
322 QUIC_BUG << "Try to get packet number space of Google QUIC packet";
323 break;
324 case IETF_QUIC_SHORT_HEADER_PACKET:
325 return APPLICATION_DATA;
326 case IETF_QUIC_LONG_HEADER_PACKET:
327 switch (header.long_packet_type) {
328 case INITIAL:
329 return INITIAL_DATA;
330 case HANDSHAKE:
331 return HANDSHAKE_DATA;
332 case ZERO_RTT_PROTECTED:
333 return APPLICATION_DATA;
334 case VERSION_NEGOTIATION:
335 case RETRY:
336 case INVALID_PACKET_TYPE:
337 QUIC_BUG << "Try to get packet number space of long header type: "
338 << QuicUtils::QuicLongHeaderTypetoString(
339 header.long_packet_type);
340 break;
341 }
342 }
343
344 return NUM_PACKET_NUMBER_SPACES;
345}
346
zhongyi546cc452019-04-12 15:27:49 -0700347EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
348 switch (header.form) {
349 case GOOGLE_QUIC_PACKET:
350 QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header";
351 break;
352 case IETF_QUIC_SHORT_HEADER_PACKET:
353 return ENCRYPTION_FORWARD_SECURE;
354 case IETF_QUIC_LONG_HEADER_PACKET:
355 switch (header.long_packet_type) {
356 case INITIAL:
357 return ENCRYPTION_INITIAL;
358 case HANDSHAKE:
359 return ENCRYPTION_HANDSHAKE;
360 case ZERO_RTT_PROTECTED:
361 return ENCRYPTION_ZERO_RTT;
362 case VERSION_NEGOTIATION:
363 case RETRY:
364 case INVALID_PACKET_TYPE:
365 QUIC_BUG << "No encryption used with type "
366 << QuicUtils::QuicLongHeaderTypetoString(
367 header.long_packet_type);
368 }
369 }
370 return NUM_ENCRYPTION_LEVELS;
371}
372
QUICHE teama6ef0a62019-03-07 20:34:33 -0500373QuicStringPiece TruncateErrorString(QuicStringPiece error) {
374 if (error.length() <= kMaxErrorStringLength) {
375 return error;
376 }
377 return QuicStringPiece(error.data(), kMaxErrorStringLength);
378}
379
380size_t TruncatedErrorStringSize(const QuicStringPiece& error) {
381 if (error.length() < kMaxErrorStringLength) {
382 return error.length();
383 }
384 return kMaxErrorStringLength;
385}
386
387uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) {
388 if (length == 0) {
389 return 0;
390 }
391 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
392}
393
394bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
395 size_t length = packet_number_length;
396 return length == 1 || length == 2 || length == 4 || length == 6 ||
397 length == 8;
398}
399
400bool IsValidFullPacketNumber(uint64_t full_packet_number,
401 QuicTransportVersion version) {
QUICHE team577718a2019-03-20 09:00:59 -0700402 return full_packet_number > 0 || version == QUIC_VERSION_99;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500403}
404
dschinazi1f485a12019-05-13 11:57:01 -0700405bool AppendIetfConnectionIds(bool version_flag,
406 QuicConnectionId destination_connection_id,
407 QuicConnectionId source_connection_id,
408 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500409 if (!version_flag) {
410 return writer->WriteConnectionId(destination_connection_id);
411 }
412
413 // Compute connection ID length byte.
414 uint8_t dcil = GetConnectionIdLengthValue(
415 static_cast<QuicConnectionIdLength>(destination_connection_id.length()));
416 uint8_t scil = GetConnectionIdLengthValue(
417 static_cast<QuicConnectionIdLength>(source_connection_id.length()));
418 uint8_t connection_id_length = dcil << 4 | scil;
419
420 return writer->WriteUInt8(connection_id_length) &&
421 writer->WriteConnectionId(destination_connection_id) &&
422 writer->WriteConnectionId(source_connection_id);
423}
424
425enum class DroppedPacketReason {
426 // General errors
427 INVALID_PUBLIC_HEADER,
428 VERSION_MISMATCH,
429 // Version negotiation packet errors
430 INVALID_VERSION_NEGOTIATION_PACKET,
431 // Public reset packet errors, pre-v44
432 INVALID_PUBLIC_RESET_PACKET,
433 // Data packet errors
434 INVALID_PACKET_NUMBER,
435 INVALID_DIVERSIFICATION_NONCE,
436 DECRYPTION_FAILURE,
437 NUM_REASONS,
438};
439
440void RecordDroppedPacketReason(DroppedPacketReason reason) {
441 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
442 DroppedPacketReason::NUM_REASONS,
443 "The reason a packet was not processed. Recorded "
444 "each time such a packet is dropped");
445}
446
fayangccbab732019-05-13 10:11:25 -0700447PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) {
448 return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
449 : IETF_QUIC_SHORT_HEADER_PACKET;
450}
451
QUICHE teama6ef0a62019-03-07 20:34:33 -0500452} // namespace
453
454QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
455 QuicTime creation_time,
456 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700457 uint8_t expected_server_connection_id_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -0500458 : visitor_(nullptr),
459 error_(QUIC_NO_ERROR),
dschinazi7b9278c2019-05-20 07:36:21 -0700460 last_serialized_server_connection_id_(EmptyQuicConnectionId()),
dschinazi346b7ce2019-06-05 01:38:18 -0700461 last_serialized_client_connection_id_(EmptyQuicConnectionId()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500462 version_(PROTOCOL_UNSUPPORTED, QUIC_VERSION_UNSUPPORTED),
463 supported_versions_(supported_versions),
QUICHE team6987b4a2019-03-15 16:23:04 -0700464 decrypter_level_(ENCRYPTION_INITIAL),
QUICHE team76086e42019-03-25 15:12:29 -0700465 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500466 alternative_decrypter_latch_(false),
467 perspective_(perspective),
468 validate_flags_(true),
469 process_timestamps_(false),
470 creation_time_(creation_time),
471 last_timestamp_(QuicTime::Delta::Zero()),
472 first_sending_packet_number_(FirstSendingPacketNumber()),
473 data_producer_(nullptr),
474 infer_packet_header_type_from_version_(perspective ==
475 Perspective::IS_CLIENT),
dschinazi8ff74822019-05-28 16:37:20 -0700476 expected_server_connection_id_length_(
477 expected_server_connection_id_length),
dschinazi346b7ce2019-06-05 01:38:18 -0700478 expected_client_connection_id_length_(0),
nharper55fa6132019-05-07 19:37:21 -0700479 supports_multiple_packet_number_spaces_(false),
fkastenholz4dc4ba32019-07-30 09:55:25 -0700480 last_written_packet_number_length_(0),
481 peer_ack_delay_exponent_(kDefaultAckDelayExponent),
482 local_ack_delay_exponent_(kDefaultAckDelayExponent) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500483 DCHECK(!supported_versions.empty());
484 version_ = supported_versions_[0];
QUICHE team76086e42019-03-25 15:12:29 -0700485 decrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullDecrypter>(perspective);
QUICHE team6987b4a2019-03-15 16:23:04 -0700486 encrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullEncrypter>(perspective);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500487}
488
489QuicFramer::~QuicFramer() {}
490
491// static
492size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
493 QuicStreamId stream_id,
494 QuicStreamOffset offset,
495 bool last_frame_in_packet,
496 QuicPacketLength data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700497 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500498 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
499 (last_frame_in_packet
500 ? 0
501 : QuicDataWriter::GetVarInt62Len(data_length)) +
502 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
503 }
504 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
505 GetStreamOffsetSize(version, offset) +
506 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
507}
508
509// static
510size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
511 QuicPacketLength data_length) {
512 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
513 QuicDataWriter::GetVarInt62Len(data_length);
514}
515
516// static
517size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
518 bool last_frame_in_packet,
519 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700520 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500521 << "Try to serialize MESSAGE frame in " << version;
522 return kQuicFrameTypeSize +
523 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
524 length;
525}
526
527// static
528size_t QuicFramer::GetMinAckFrameSize(
529 QuicTransportVersion version,
530 QuicPacketNumberLength largest_observed_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700531 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500532 // The minimal ack frame consists of the following four fields: Largest
533 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
534 // size of each is 1 byte.
535 return kQuicFrameTypeSize + 4;
536 }
537 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
538 kQuicDeltaTimeLargestObservedSize;
539 return min_size + kQuicNumTimestampsSize;
540}
541
542// static
543size_t QuicFramer::GetStopWaitingFrameSize(
dschinazi17d42422019-06-18 16:35:07 -0700544 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500545 QuicPacketNumberLength packet_number_length) {
546 size_t min_size = kQuicFrameTypeSize + packet_number_length;
547 return min_size;
548}
549
550// static
551size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
552 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700553 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500554 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
555 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700556 kQuicFrameTypeSize +
557 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500558 }
559 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
560 kQuicErrorCodeSize;
561}
562
563// static
fkastenholza037b8b2019-05-07 06:00:05 -0700564size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500565 QuicTransportVersion version,
566 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700567 if (!VersionHasIetfQuicFrames(version)) {
568 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700569 return kQuicFrameTypeSize + kQuicErrorCodeSize +
570 kQuicErrorDetailsLengthSize +
571 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500572 }
fkastenholza037b8b2019-05-07 06:00:05 -0700573 // TODO(fkastenholz): For complete support of IETF QUIC CONNECTION_CLOSE,
574 // check if the frame is a Transport close and if the frame's
575 // extracted_error_code is not QUIC_IETF_GQUIC_ERROR_MISSING. If so,
576 // extend the error string to include " QuicErrorCode: #"
577 const size_t truncated_error_string_size =
578 TruncatedErrorStringSize(frame.error_details);
fkastenholzd57d3f92019-07-16 09:05:17 -0700579 uint64_t close_code = 0;
580 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
581 close_code = static_cast<uint64_t>(frame.transport_error_code);
582 } else if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
583 close_code = static_cast<uint64_t>(frame.application_error_code);
584 }
fkastenholza037b8b2019-05-07 06:00:05 -0700585 const size_t frame_size =
586 truncated_error_string_size +
587 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholzd57d3f92019-07-16 09:05:17 -0700588 kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(close_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700589 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
590 return frame_size;
591 }
592 // frame includes the transport_close_frame_type, so include its length.
593 return frame_size +
594 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500595}
596
597// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500598size_t QuicFramer::GetMinGoAwayFrameSize() {
599 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
600 kQuicMaxStreamIdSize;
601}
602
603// static
604size_t QuicFramer::GetWindowUpdateFrameSize(
605 QuicTransportVersion version,
606 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700607 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500608 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
609 }
610 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
611 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
612 return kQuicFrameTypeSize +
613 QuicDataWriter::GetVarInt62Len(frame.byte_offset);
614 }
615 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
616 // fields.
617 return kQuicFrameTypeSize +
618 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
619 QuicDataWriter::GetVarInt62Len(frame.stream_id);
620}
621
622// static
623size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700624 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700625 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500626 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700627 << ", which does not support IETF Frames, and tried to serialize "
628 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500629 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700630 return kQuicFrameTypeSize +
631 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500632}
633
634// static
635size_t QuicFramer::GetStreamsBlockedFrameSize(
636 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700637 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700638 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500639 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700640 << ", which does not support IETF frames, and tried to serialize "
641 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500642 }
643
fkastenholz3c4eabf2019-04-22 07:49:59 -0700644 return kQuicFrameTypeSize +
645 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500646}
647
648// static
649size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
650 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700651 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500652 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
653 }
654 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
655 // return size of IETF QUIC Blocked frame
656 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
657 }
658 // return size of IETF QUIC Stream Blocked frame.
659 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
660 QuicDataWriter::GetVarInt62Len(frame.stream_id);
661}
662
663// static
664size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
665 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700666 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500667}
668
669// static
670size_t QuicFramer::GetPathChallengeFrameSize(
671 const QuicPathChallengeFrame& frame) {
672 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
673}
674
675// static
676size_t QuicFramer::GetPathResponseFrameSize(
677 const QuicPathResponseFrame& frame) {
678 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
679}
680
681// static
682size_t QuicFramer::GetRetransmittableControlFrameSize(
683 QuicTransportVersion version,
684 const QuicFrame& frame) {
685 switch (frame.type) {
686 case PING_FRAME:
687 // Ping has no payload.
688 return kQuicFrameTypeSize;
689 case RST_STREAM_FRAME:
690 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
691 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700692 return GetConnectionCloseFrameSize(version,
693 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500694 case GOAWAY_FRAME:
695 return GetMinGoAwayFrameSize() +
696 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
697 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700698 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500699 // GetWindowUpdateFrameSize figures this out and returns the correct
700 // length.
701 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
702 case BLOCKED_FRAME:
703 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500704 case NEW_CONNECTION_ID_FRAME:
705 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
706 case RETIRE_CONNECTION_ID_FRAME:
707 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
708 case NEW_TOKEN_FRAME:
709 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700710 case MAX_STREAMS_FRAME:
711 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
712 case STREAMS_BLOCKED_FRAME:
713 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500714 case PATH_RESPONSE_FRAME:
715 return GetPathResponseFrameSize(*frame.path_response_frame);
716 case PATH_CHALLENGE_FRAME:
717 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
718 case STOP_SENDING_FRAME:
719 return GetStopSendingFrameSize(*frame.stop_sending_frame);
720
721 case STREAM_FRAME:
722 case ACK_FRAME:
723 case STOP_WAITING_FRAME:
724 case MTU_DISCOVERY_FRAME:
725 case PADDING_FRAME:
726 case MESSAGE_FRAME:
727 case CRYPTO_FRAME:
728 case NUM_FRAME_TYPES:
729 DCHECK(false);
730 return 0;
731 }
732
733 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
734 DCHECK(false);
735 return 0;
736}
737
738// static
739size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
740 // Sizes are 1 through 4 bytes.
741 for (int i = 1; i <= 4; ++i) {
742 stream_id >>= 8;
743 if (stream_id == 0) {
744 return i;
745 }
746 }
747 QUIC_BUG << "Failed to determine StreamIDSize.";
748 return 4;
749}
750
751// static
dschinazi17d42422019-06-18 16:35:07 -0700752size_t QuicFramer::GetStreamOffsetSize(QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500753 QuicStreamOffset offset) {
754 // 0 is a special case.
755 if (offset == 0) {
756 return 0;
757 }
758 // 2 through 8 are the remaining sizes.
759 offset >>= 8;
760 for (int i = 2; i <= 8; ++i) {
761 offset >>= 8;
762 if (offset == 0) {
763 return i;
764 }
765 }
766 QUIC_BUG << "Failed to determine StreamOffsetSize.";
767 return 8;
768}
769
770// static
771size_t QuicFramer::GetNewConnectionIdFrameSize(
772 const QuicNewConnectionIdFrame& frame) {
773 return kQuicFrameTypeSize +
774 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700775 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500776 kConnectionIdLengthSize + frame.connection_id.length() +
777 sizeof(frame.stateless_reset_token);
778}
779
780// static
781size_t QuicFramer::GetRetireConnectionIdFrameSize(
782 const QuicRetireConnectionIdFrame& frame) {
783 return kQuicFrameTypeSize +
784 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
785}
786
787// static
788size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
789 return kQuicFrameTypeSize +
790 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
791 frame.token.length();
792}
793
794// TODO(nharper): Change this method to take a ParsedQuicVersion.
795bool QuicFramer::IsSupportedTransportVersion(
796 const QuicTransportVersion version) const {
797 for (ParsedQuicVersion supported_version : supported_versions_) {
798 if (version == supported_version.transport_version) {
799 return true;
800 }
801 }
802 return false;
803}
804
805bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
806 for (const ParsedQuicVersion& supported_version : supported_versions_) {
807 if (version == supported_version) {
808 return true;
809 }
810 }
811 return false;
812}
813
814size_t QuicFramer::GetSerializedFrameLength(
815 const QuicFrame& frame,
816 size_t free_bytes,
817 bool first_frame,
818 bool last_frame,
819 QuicPacketNumberLength packet_number_length) {
820 // Prevent a rare crash reported in b/19458523.
821 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
822 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
823 << free_bytes << " first_frame:" << first_frame
824 << " last_frame:" << last_frame
825 << " seq num length:" << packet_number_length;
826 set_error(QUIC_INTERNAL_ERROR);
827 visitor_->OnError(this);
828 return 0;
829 }
830 if (frame.type == PADDING_FRAME) {
831 if (frame.padding_frame.num_padding_bytes == -1) {
832 // Full padding to the end of the packet.
833 return free_bytes;
834 } else {
835 // Lite padding.
836 return free_bytes <
837 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
838 ? free_bytes
839 : frame.padding_frame.num_padding_bytes;
840 }
841 }
842
843 size_t frame_len =
844 ComputeFrameLength(frame, last_frame, packet_number_length);
845 if (frame_len <= free_bytes) {
846 // Frame fits within packet. Note that acks may be truncated.
847 return frame_len;
848 }
849 // Only truncate the first frame in a packet, so if subsequent ones go
850 // over, stop including more frames.
851 if (!first_frame) {
852 return 0;
853 }
854 bool can_truncate =
855 frame.type == ACK_FRAME &&
856 free_bytes >= GetMinAckFrameSize(version_.transport_version,
857 PACKET_6BYTE_PACKET_NUMBER);
858 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700859 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500860 // Note that we may not use every byte of the writer in this case.
861 QUIC_DLOG(INFO) << ENDPOINT
862 << "Truncating large frame, free bytes: " << free_bytes;
863 return free_bytes;
864 }
865 return 0;
866}
867
868QuicFramer::AckFrameInfo::AckFrameInfo()
869 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
870
871QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
872
873QuicFramer::AckFrameInfo::~AckFrameInfo() {}
874
875bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
876 QuicDataWriter* writer,
877 size_t length_field_offset,
878 EncryptionLevel level) {
879 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
880 !header.version_flag || length_field_offset == 0) {
881 return true;
882 }
883 if (writer->length() < length_field_offset ||
884 writer->length() - length_field_offset <
885 kQuicDefaultLongHeaderLengthLength) {
886 set_detailed_error("Invalid length_field_offset.");
887 QUIC_BUG << "Invalid length_field_offset.";
888 return false;
889 }
890 size_t length_to_write = writer->length() - length_field_offset -
891 kQuicDefaultLongHeaderLengthLength;
892 // Add length of auth tag.
893 length_to_write = GetCiphertextSize(level, length_to_write);
894
895 QuicDataWriter length_writer(writer->length() - length_field_offset,
896 writer->data() + length_field_offset);
897 if (!length_writer.WriteVarInt62(length_to_write,
898 kQuicDefaultLongHeaderLengthLength)) {
899 set_detailed_error("Failed to overwrite long header length.");
900 QUIC_BUG << "Failed to overwrite long header length.";
901 return false;
902 }
903 return true;
904}
905
906size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
907 const QuicFrames& frames,
908 char* buffer,
909 size_t packet_length,
910 EncryptionLevel level) {
911 QuicDataWriter writer(packet_length, buffer);
912 size_t length_field_offset = 0;
913 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
914 QUIC_BUG << "AppendPacketHeader failed";
915 return 0;
916 }
917
fkastenholz305e1732019-06-18 05:01:22 -0700918 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500919 if (AppendIetfFrames(frames, &writer) == 0) {
920 return 0;
921 }
922 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
923 level)) {
924 return 0;
925 }
926 return writer.length();
927 }
928 // TODO(dschinazi) if we enable long header lengths before v99, we need to
929 // add support for fixing up lengths in QuicFramer::BuildDataPacket.
930 DCHECK(!QuicVersionHasLongHeaderLengths(transport_version()));
931
932 size_t i = 0;
933 for (const QuicFrame& frame : frames) {
934 // Determine if we should write stream frame length in header.
935 const bool last_frame_in_packet = i == frames.size() - 1;
936 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
937 QUIC_BUG << "AppendTypeByte failed";
938 return 0;
939 }
940
941 switch (frame.type) {
942 case PADDING_FRAME:
943 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
944 QUIC_BUG << "AppendPaddingFrame of "
945 << frame.padding_frame.num_padding_bytes << " failed";
946 return 0;
947 }
948 break;
949 case STREAM_FRAME:
950 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
951 &writer)) {
952 QUIC_BUG << "AppendStreamFrame failed";
953 return 0;
954 }
955 break;
956 case ACK_FRAME:
957 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
958 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
959 return 0;
960 }
961 break;
962 case STOP_WAITING_FRAME:
963 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
964 &writer)) {
965 QUIC_BUG << "AppendStopWaitingFrame failed";
966 return 0;
967 }
968 break;
969 case MTU_DISCOVERY_FRAME:
970 // MTU discovery frames are serialized as ping frames.
971 QUIC_FALLTHROUGH_INTENDED;
972 case PING_FRAME:
973 // Ping has no payload.
974 break;
975 case RST_STREAM_FRAME:
976 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
977 QUIC_BUG << "AppendRstStreamFrame failed";
978 return 0;
979 }
980 break;
981 case CONNECTION_CLOSE_FRAME:
982 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
983 &writer)) {
984 QUIC_BUG << "AppendConnectionCloseFrame failed";
985 return 0;
986 }
987 break;
988 case GOAWAY_FRAME:
989 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
990 QUIC_BUG << "AppendGoAwayFrame failed";
991 return 0;
992 }
993 break;
994 case WINDOW_UPDATE_FRAME:
995 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
996 QUIC_BUG << "AppendWindowUpdateFrame failed";
997 return 0;
998 }
999 break;
1000 case BLOCKED_FRAME:
1001 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
1002 QUIC_BUG << "AppendBlockedFrame failed";
1003 return 0;
1004 }
1005 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001006 case NEW_CONNECTION_ID_FRAME:
1007 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001008 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001009 return RaiseError(QUIC_INTERNAL_ERROR);
1010 case RETIRE_CONNECTION_ID_FRAME:
1011 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001012 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
1013 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001014 return RaiseError(QUIC_INTERNAL_ERROR);
1015 case NEW_TOKEN_FRAME:
1016 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001017 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001018 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07001019 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001020 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001021 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001022 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07001023 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001024 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001025 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001026 return RaiseError(QUIC_INTERNAL_ERROR);
1027 case PATH_RESPONSE_FRAME:
1028 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001029 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001030 return RaiseError(QUIC_INTERNAL_ERROR);
1031 case PATH_CHALLENGE_FRAME:
1032 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001033 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001034 return RaiseError(QUIC_INTERNAL_ERROR);
1035 case STOP_SENDING_FRAME:
1036 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001037 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001038 return RaiseError(QUIC_INTERNAL_ERROR);
1039 case MESSAGE_FRAME:
1040 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1041 last_frame_in_packet, &writer)) {
1042 QUIC_BUG << "AppendMessageFrame failed";
1043 return 0;
1044 }
1045 break;
1046 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -07001047 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001048 set_detailed_error(
1049 "Attempt to append CRYPTO frame in version prior to 47.");
1050 return RaiseError(QUIC_INTERNAL_ERROR);
1051 }
1052 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1053 QUIC_BUG << "AppendCryptoFrame failed";
1054 return 0;
1055 }
1056 break;
1057 default:
1058 RaiseError(QUIC_INVALID_FRAME_DATA);
1059 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1060 return 0;
1061 }
1062 ++i;
1063 }
1064
1065 return writer.length();
1066}
1067
1068size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1069 QuicDataWriter* writer) {
1070 size_t i = 0;
1071 for (const QuicFrame& frame : frames) {
1072 // Determine if we should write stream frame length in header.
1073 const bool last_frame_in_packet = i == frames.size() - 1;
1074 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1075 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1076 return 0;
1077 }
1078
1079 switch (frame.type) {
1080 case PADDING_FRAME:
1081 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1082 QUIC_BUG << "AppendPaddingFrame of "
1083 << frame.padding_frame.num_padding_bytes
1084 << " failed: " << detailed_error();
1085 return 0;
1086 }
1087 break;
1088 case STREAM_FRAME:
1089 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1090 writer)) {
1091 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1092 return 0;
1093 }
1094 break;
1095 case ACK_FRAME:
1096 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001097 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1098 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001099 return 0;
1100 }
1101 break;
1102 case STOP_WAITING_FRAME:
1103 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001104 "Attempt to append STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001105 return RaiseError(QUIC_INTERNAL_ERROR);
1106 case MTU_DISCOVERY_FRAME:
1107 // MTU discovery frames are serialized as ping frames.
1108 QUIC_FALLTHROUGH_INTENDED;
1109 case PING_FRAME:
1110 // Ping has no payload.
1111 break;
1112 case RST_STREAM_FRAME:
1113 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1114 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1115 return 0;
1116 }
1117 break;
1118 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001119 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1120 writer)) {
1121 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1122 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001123 return 0;
1124 }
1125 break;
1126 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001127 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001128 return RaiseError(QUIC_INTERNAL_ERROR);
1129 case WINDOW_UPDATE_FRAME:
1130 // Depending on whether there is a stream ID or not, will be either a
1131 // MAX STREAM DATA frame or a MAX DATA frame.
1132 if (frame.window_update_frame->stream_id ==
1133 QuicUtils::GetInvalidStreamId(transport_version())) {
1134 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1135 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1136 return 0;
1137 }
1138 } else {
1139 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1140 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1141 return 0;
1142 }
1143 }
1144 break;
1145 case BLOCKED_FRAME:
1146 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1147 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1148 return 0;
1149 }
1150 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001151 case MAX_STREAMS_FRAME:
1152 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001153 QUIC_BUG << "AppendMaxStreamsFrame failed" << detailed_error();
1154 return 0;
1155 }
1156 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001157 case STREAMS_BLOCKED_FRAME:
1158 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001159 QUIC_BUG << "AppendStreamsBlockedFrame failed" << detailed_error();
1160 return 0;
1161 }
1162 break;
1163 case NEW_CONNECTION_ID_FRAME:
1164 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1165 writer)) {
1166 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1167 return 0;
1168 }
1169 break;
1170 case RETIRE_CONNECTION_ID_FRAME:
1171 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1172 writer)) {
1173 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1174 << detailed_error();
1175 return 0;
1176 }
1177 break;
1178 case NEW_TOKEN_FRAME:
1179 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1180 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1181 return 0;
1182 }
1183 break;
1184 case STOP_SENDING_FRAME:
1185 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1186 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1187 return 0;
1188 }
1189 break;
1190 case PATH_CHALLENGE_FRAME:
1191 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1192 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1193 return 0;
1194 }
1195 break;
1196 case PATH_RESPONSE_FRAME:
1197 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1198 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1199 return 0;
1200 }
1201 break;
1202 case MESSAGE_FRAME:
1203 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1204 last_frame_in_packet, writer)) {
1205 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1206 return 0;
1207 }
1208 break;
1209 case CRYPTO_FRAME:
1210 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1211 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1212 return 0;
1213 }
1214 break;
1215 default:
1216 RaiseError(QUIC_INVALID_FRAME_DATA);
1217 set_detailed_error("Tried to append unknown frame type.");
1218 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1219 return 0;
1220 }
1221 ++i;
1222 }
1223
1224 return writer->length();
1225}
1226
rch67cb9df2019-03-26 16:52:07 -07001227size_t QuicFramer::BuildConnectivityProbingPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001228 const QuicPacketHeader& header,
1229 char* buffer,
1230 size_t packet_length,
1231 EncryptionLevel level) {
1232 QuicFrames frames;
1233
1234 // Write a PING frame, which has no data payload.
1235 QuicPingFrame ping_frame;
1236 frames.push_back(QuicFrame(ping_frame));
1237
1238 // Add padding to the rest of the packet.
1239 QuicPaddingFrame padding_frame;
1240 frames.push_back(QuicFrame(padding_frame));
1241
1242 return BuildDataPacket(header, frames, buffer, packet_length, level);
1243}
1244
QUICHE teama6ef0a62019-03-07 20:34:33 -05001245size_t QuicFramer::BuildPaddedPathChallengePacket(
1246 const QuicPacketHeader& header,
1247 char* buffer,
1248 size_t packet_length,
1249 QuicPathFrameBuffer* payload,
1250 QuicRandom* randomizer,
1251 EncryptionLevel level) {
fkastenholz305e1732019-06-18 05:01:22 -07001252 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001253 QUIC_BUG << "Attempt to build a PATH_CHALLENGE Connectivity Probing "
1254 "packet and not doing IETF QUIC";
1255 return 0;
1256 }
1257 QuicFrames frames;
1258
1259 // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1260 randomizer->RandBytes(payload->data(), payload->size());
1261
1262 QuicPathChallengeFrame path_challenge_frame(0, *payload);
1263 frames.push_back(QuicFrame(&path_challenge_frame));
1264
1265 // Add padding to the rest of the packet in order to assess Path MTU
1266 // characteristics.
1267 QuicPaddingFrame padding_frame;
1268 frames.push_back(QuicFrame(padding_frame));
1269
1270 return BuildDataPacket(header, frames, buffer, packet_length, level);
1271}
1272
1273size_t QuicFramer::BuildPathResponsePacket(
1274 const QuicPacketHeader& header,
1275 char* buffer,
1276 size_t packet_length,
1277 const QuicDeque<QuicPathFrameBuffer>& payloads,
1278 const bool is_padded,
1279 EncryptionLevel level) {
1280 if (payloads.empty()) {
1281 QUIC_BUG
1282 << "Attempt to generate connectivity response with no request payloads";
1283 return 0;
1284 }
fkastenholz305e1732019-06-18 05:01:22 -07001285 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001286 QUIC_BUG << "Attempt to build a PATH_RESPONSE Connectivity Probing "
1287 "packet and not doing IETF QUIC";
1288 return 0;
1289 }
1290
1291 std::vector<std::unique_ptr<QuicPathResponseFrame>> path_response_frames;
1292 for (const QuicPathFrameBuffer& payload : payloads) {
1293 // Note that the control frame ID can be 0 since this is not retransmitted.
1294 path_response_frames.push_back(
1295 QuicMakeUnique<QuicPathResponseFrame>(0, payload));
1296 }
1297
1298 QuicFrames frames;
1299 for (const std::unique_ptr<QuicPathResponseFrame>& path_response_frame :
1300 path_response_frames) {
1301 frames.push_back(QuicFrame(path_response_frame.get()));
1302 }
1303
1304 if (is_padded) {
1305 // Add padding to the rest of the packet in order to assess Path MTU
1306 // characteristics.
1307 QuicPaddingFrame padding_frame;
1308 frames.push_back(QuicFrame(padding_frame));
1309 }
1310
1311 return BuildDataPacket(header, frames, buffer, packet_length, level);
1312}
1313
1314// static
1315std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1316 const QuicPublicResetPacket& packet) {
1317 CryptoHandshakeMessage reset;
1318 reset.set_tag(kPRST);
1319 reset.SetValue(kRNON, packet.nonce_proof);
1320 if (packet.client_address.host().address_family() !=
1321 IpAddressFamily::IP_UNSPEC) {
1322 // packet.client_address is non-empty.
1323 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001324 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001325 if (serialized_address.empty()) {
1326 return nullptr;
1327 }
1328 reset.SetStringPiece(kCADR, serialized_address);
1329 }
1330 if (!packet.endpoint_id.empty()) {
1331 reset.SetStringPiece(kEPID, packet.endpoint_id);
1332 }
1333 const QuicData& reset_serialized = reset.GetSerialized();
1334
1335 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1336 reset_serialized.length();
1337 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001338 QuicDataWriter writer(len, buffer.get());
1339
1340 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1341 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1342 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1343 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1344 if (!writer.WriteUInt8(flags)) {
1345 return nullptr;
1346 }
1347
1348 if (!writer.WriteConnectionId(packet.connection_id)) {
1349 return nullptr;
1350 }
1351
1352 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1353 return nullptr;
1354 }
1355
1356 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1357}
1358
1359// static
1360std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001361 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001362 QuicUint128 stateless_reset_token) {
1363 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1364 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1365 sizeof(stateless_reset_token);
1366 std::unique_ptr<char[]> buffer(new char[len]);
1367 QuicDataWriter writer(len, buffer.get());
1368
1369 uint8_t type = 0;
1370 type |= FLAGS_FIXED_BIT;
1371 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1372 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayangf36e29d2019-06-06 14:03:40 -07001373 type |= PacketNumberLengthToOnWireValue(QUIC_VERSION_UNSUPPORTED,
1374 PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001375
1376 // Append type byte.
1377 if (!writer.WriteUInt8(type)) {
1378 return nullptr;
1379 }
1380 // Append random bytes.
1381 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1382 kMinRandomBytesLengthInStatelessReset)) {
1383 return nullptr;
1384 }
1385
1386 // Append stateless reset token.
1387 if (!writer.WriteBytes(&stateless_reset_token,
1388 sizeof(stateless_reset_token))) {
1389 return nullptr;
1390 }
1391 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1392}
1393
1394// static
1395std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001396 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001397 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001398 bool ietf_quic,
1399 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001400 ParsedQuicVersionVector wire_versions = versions;
1401 if (!GetQuicReloadableFlag(quic_version_negotiation_grease)) {
1402 if (wire_versions.empty()) {
1403 wire_versions = {QuicVersionReservedForNegotiation()};
1404 }
1405 } else {
1406 // Add a version reserved for negotiation as suggested by the
1407 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1408 QUIC_RELOADABLE_FLAG_COUNT_N(quic_version_negotiation_grease, 1, 2);
1409 if (wire_versions.empty()) {
1410 // Ensure that version negotiation packets we send have at least two
1411 // versions. This guarantees that, under all circumstances, all QUIC
1412 // packets we send are at least 14 bytes long.
1413 wire_versions = {QuicVersionReservedForNegotiation(),
1414 QuicVersionReservedForNegotiation()};
1415 } else {
1416 // This is not uniformely distributed but is acceptable since no security
1417 // depends on this randomness.
1418 size_t version_index = 0;
1419 const bool disable_randomness =
1420 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1421 if (!disable_randomness) {
1422 version_index = QuicRandom::GetInstance()->RandUint64() %
1423 (wire_versions.size() + 1);
1424 }
1425 wire_versions.insert(wire_versions.begin() + version_index,
1426 QuicVersionReservedForNegotiation());
1427 }
1428 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001429 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001430 return BuildIetfVersionNegotiationPacket(
1431 server_connection_id, client_connection_id, wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001432 }
dschinazib417d602019-05-29 13:08:45 -07001433
1434 // The GQUIC encoding does not support encoding client connection IDs.
1435 DCHECK(client_connection_id.IsEmpty());
1436
dschinazi1ac22cc2019-06-25 11:47:50 -07001437 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001438 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001439 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001440 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001441 QuicDataWriter writer(len, buffer.get());
1442
1443 uint8_t flags = static_cast<uint8_t>(
1444 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1445 // TODO(rch): Remove this QUIC_VERSION_32 is retired.
1446 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1447 if (!writer.WriteUInt8(flags)) {
1448 return nullptr;
1449 }
1450
dschinazi8ff74822019-05-28 16:37:20 -07001451 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001452 return nullptr;
1453 }
1454
dschinazi1ac22cc2019-06-25 11:47:50 -07001455 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001456 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001457 return nullptr;
1458 }
1459 }
1460
1461 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1462}
1463
1464// static
1465std::unique_ptr<QuicEncryptedPacket>
1466QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazib417d602019-05-29 13:08:45 -07001467 QuicConnectionId server_connection_id,
1468 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001469 const ParsedQuicVersionVector& versions) {
dschinazi5a354c92019-05-09 12:18:53 -07001470 QUIC_DVLOG(1) << "Building IETF version negotiation packet: "
1471 << ParsedQuicVersionVectorToString(versions);
dschinazib417d602019-05-29 13:08:45 -07001472 DCHECK(client_connection_id.IsEmpty() ||
1473 GetQuicRestartFlag(quic_do_not_override_connection_id));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001474 DCHECK(!versions.empty());
1475 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001476 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001477 (versions.size() + 1) * kQuicVersionSize;
1478 std::unique_ptr<char[]> buffer(new char[len]);
1479 QuicDataWriter writer(len, buffer.get());
1480
1481 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001482 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001483 if (!writer.WriteUInt8(type)) {
1484 return nullptr;
1485 }
1486
1487 if (!writer.WriteUInt32(0)) {
1488 return nullptr;
1489 }
1490
dschinazib417d602019-05-29 13:08:45 -07001491 if (!AppendIetfConnectionIds(true, client_connection_id, server_connection_id,
1492 &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001493 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001494 }
1495
1496 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001497 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001498 return nullptr;
1499 }
1500 }
1501
1502 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1503}
1504
1505bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1506 QuicDataReader reader(packet.data(), packet.length());
1507
1508 bool packet_has_ietf_packet_header = false;
1509 if (infer_packet_header_type_from_version_) {
1510 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001511 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001512 } else if (!reader.IsDoneReading()) {
1513 uint8_t type = reader.PeekByte();
1514 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1515 }
1516 if (packet_has_ietf_packet_header) {
1517 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1518 }
1519
1520 visitor_->OnPacket();
1521
1522 QuicPacketHeader header;
1523 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1524 DCHECK_NE("", detailed_error_);
1525 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1526 << detailed_error_;
1527 DCHECK_NE("", detailed_error_);
1528 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1529 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1530 }
1531
1532 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1533 // The visitor suppresses further processing of the packet.
1534 return true;
1535 }
1536
dschinazie0df3f72019-05-06 16:37:51 -07001537 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001538 if (perspective_ == Perspective::IS_CLIENT) {
1539 QUIC_DVLOG(1) << "Client received version negotiation packet";
1540 return ProcessVersionNegotiationPacket(&reader, header);
1541 } else {
1542 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1543 set_detailed_error("Server received version negotiation packet.");
1544 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1545 }
dschinazie0df3f72019-05-06 16:37:51 -07001546 }
1547
1548 if (header.version_flag && header.version != version_) {
1549 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001550 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001551 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1552 return true;
1553 }
1554 } else {
1555 // A client received a packet of a different version but that packet is
1556 // not a version negotiation packet. It is therefore invalid and dropped.
1557 QUIC_DLOG(ERROR) << "Client received unexpected version "
1558 << ParsedQuicVersionToString(header.version)
1559 << " instead of " << ParsedQuicVersionToString(version_);
1560 set_detailed_error("Client received unexpected version.");
1561 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001562 }
1563 }
1564
1565 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001566 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001567 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001568 } else if (header.reset_flag) {
1569 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001570 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001571 // The optimized decryption algorithm implementations run faster when
1572 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001573 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001574 if (packet_has_ietf_packet_header) {
1575 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
dschinazie8d7fa72019-04-05 14:44:40 -07001576 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001577 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001578 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1579 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001580 }
1581 } else {
1582 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1583 if (packet_has_ietf_packet_header) {
1584 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1585 packet.length());
1586 } else {
1587 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1588 packet.length());
1589 }
1590 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001591 << "than kMaxIncomingPacketSize. packet size:"
1592 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001593 }
1594 return rv;
1595}
1596
1597bool QuicFramer::ProcessVersionNegotiationPacket(
1598 QuicDataReader* reader,
1599 const QuicPacketHeader& header) {
1600 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1601
QUICHE team2252b702019-05-14 23:55:14 -04001602 QuicVersionNegotiationPacket packet(
1603 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001604 // Try reading at least once to raise error if the packet is invalid.
1605 do {
1606 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001607 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001608 set_detailed_error("Unable to read supported version in negotiation.");
1609 RecordDroppedPacketReason(
1610 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1611 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1612 }
nharper4fd11052019-06-04 14:23:22 -07001613 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1614 if (parsed_version != UnsupportedQuicVersion()) {
1615 packet.versions.push_back(parsed_version);
1616 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001617 } while (!reader->IsDoneReading());
1618
dschinazi5a354c92019-05-09 12:18:53 -07001619 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1620 << ParsedQuicVersionVectorToString(packet.versions);
1621
QUICHE teama6ef0a62019-03-07 20:34:33 -05001622 visitor_->OnVersionNegotiationPacket(packet);
1623 return true;
1624}
1625
dschinazi244f6dc2019-05-06 15:45:16 -07001626bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1627 const QuicPacketHeader& header) {
1628 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1629
1630 // Parse Original Destination Connection ID Length.
1631 uint8_t odcil = header.type_byte & 0xf;
1632 if (odcil != 0) {
1633 odcil += kConnectionIdLengthAdjustment;
1634 }
1635
1636 // Parse Original Destination Connection ID.
1637 QuicConnectionId original_destination_connection_id;
1638 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1639 set_detailed_error("Unable to read Original Destination ConnectionId.");
1640 return false;
1641 }
1642
1643 QuicStringPiece retry_token = reader->ReadRemainingPayload();
1644 visitor_->OnRetryPacket(original_destination_connection_id,
1645 header.source_connection_id, retry_token);
1646 return true;
1647}
1648
QUICHE teama6ef0a62019-03-07 20:34:33 -05001649bool QuicFramer::MaybeProcessIetfInitialRetryToken(
1650 QuicDataReader* encrypted_reader,
1651 QuicPacketHeader* header) {
1652 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1653 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1654 header->long_packet_type != INITIAL) {
1655 return true;
1656 }
1657 uint64_t retry_token_length = 0;
1658 header->retry_token_length_length = encrypted_reader->PeekVarInt62Length();
1659 if (!encrypted_reader->ReadVarInt62(&retry_token_length)) {
1660 set_detailed_error("Unable to read INITIAL retry token length.");
1661 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1662 }
1663 header->retry_token = encrypted_reader->PeekRemainingPayload();
1664 // Safety check to avoid spending ressources if malformed.
1665 // At this point header->retry_token contains the rest of the packet
1666 // so its length() is the amount of data remaining in the packet.
1667 if (retry_token_length > header->retry_token.length()) {
1668 set_detailed_error("INITIAL token length longer than packet.");
1669 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1670 }
1671 // Resize retry_token to make it only contain the retry token.
1672 header->retry_token.remove_suffix(header->retry_token.length() -
1673 retry_token_length);
1674 // Advance encrypted_reader by retry_token_length.
1675 uint8_t wasted_byte;
1676 for (uint64_t i = 0; i < retry_token_length; ++i) {
1677 if (!encrypted_reader->ReadUInt8(&wasted_byte)) {
1678 set_detailed_error("Unable to read INITIAL retry token.");
1679 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1680 }
1681 }
1682 return true;
1683}
1684
1685// Seeks the current packet to check for a coalesced packet at the end.
1686// If the IETF length field only spans part of the outer packet,
1687// then there is a coalesced packet after this one.
1688void QuicFramer::MaybeProcessCoalescedPacket(
1689 const QuicDataReader& encrypted_reader,
1690 uint64_t remaining_bytes_length,
1691 const QuicPacketHeader& header) {
1692 if (header.remaining_packet_length >= remaining_bytes_length) {
1693 // There is no coalesced packet.
1694 return;
1695 }
1696
1697 QuicStringPiece remaining_data = encrypted_reader.PeekRemainingPayload();
1698 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1699
1700 const char* coalesced_data =
1701 remaining_data.data() + header.remaining_packet_length;
1702 uint64_t coalesced_data_length =
1703 remaining_bytes_length - header.remaining_packet_length;
1704 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1705
1706 QuicPacketHeader coalesced_header;
1707 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1708 QUIC_PEER_BUG << ENDPOINT
1709 << "Failed to parse received coalesced header of length "
1710 << coalesced_data_length << ": "
1711 << QuicTextUtils::HexEncode(coalesced_data,
1712 coalesced_data_length)
1713 << " previous header was " << header;
1714 return;
1715 }
1716
1717 if (coalesced_header.destination_connection_id !=
1718 header.destination_connection_id ||
1719 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1720 coalesced_header.version != header.version)) {
1721 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1722 << coalesced_header << " previous header was " << header;
1723 return;
1724 }
1725
1726 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1727 /*owns_buffer=*/false);
1728 visitor_->OnCoalescedPacket(coalesced_packet);
1729}
1730
1731bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1732 QuicPacketHeader* header) {
1733 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1734 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1735 (header->long_packet_type != INITIAL &&
1736 header->long_packet_type != HANDSHAKE &&
1737 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1738 return true;
1739 }
1740 header->length_length = encrypted_reader->PeekVarInt62Length();
1741 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1742 set_detailed_error("Unable to read long header payload length.");
1743 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1744 }
1745 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1746 if (header->remaining_packet_length > remaining_bytes_length) {
1747 set_detailed_error("Long header payload length longer than packet.");
1748 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1749 }
1750
1751 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1752 *header);
1753
1754 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1755 set_detailed_error("Length TruncateRemaining failed.");
1756 QUIC_BUG << "Length TruncateRemaining failed.";
1757 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1758 }
1759 return true;
1760}
1761
1762bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1763 QuicPacketHeader* header,
1764 const QuicEncryptedPacket& packet,
1765 char* decrypted_buffer,
1766 size_t buffer_length) {
1767 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1768 DCHECK(!header->has_possible_stateless_reset_token);
1769 header->retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1770 header->retry_token = QuicStringPiece();
1771 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1772 header->remaining_packet_length = 0;
1773 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1774 perspective_ == Perspective::IS_CLIENT) {
1775 // Peek possible stateless reset token. Will only be used on decryption
1776 // failure.
1777 QuicStringPiece remaining = encrypted_reader->PeekRemainingPayload();
1778 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1779 header->has_possible_stateless_reset_token = true;
1780 memcpy(&header->possible_stateless_reset_token,
1781 &remaining.data()[remaining.length() -
1782 sizeof(header->possible_stateless_reset_token)],
1783 sizeof(header->possible_stateless_reset_token));
1784 }
1785 }
1786
1787 if (!MaybeProcessIetfInitialRetryToken(encrypted_reader, header)) {
1788 return false;
1789 }
1790
1791 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1792 return false;
1793 }
1794
nharper55fa6132019-05-07 19:37:21 -07001795 QuicStringPiece associated_data;
1796 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001797 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1798 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001799 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1800 header->long_packet_type == INITIAL ||
1801 header->long_packet_type == HANDSHAKE ||
1802 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001803 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001804 QuicPacketNumber base_packet_number;
1805 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001806 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1807 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1808 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1809 }
1810 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001811 } else {
1812 base_packet_number = largest_packet_number_;
1813 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001814 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001815 bool hp_removal_failed = false;
1816 if (version_.HasHeaderProtection()) {
1817 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1818 &full_packet_number, &ad_storage)) {
1819 hp_removal_failed = true;
1820 }
1821 associated_data = QuicStringPiece(ad_storage.data(), ad_storage.size());
1822 } else if (!ProcessAndCalculatePacketNumber(
1823 encrypted_reader, header->packet_number_length,
1824 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001825 set_detailed_error("Unable to read packet number.");
1826 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1827 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1828 }
1829
nharper55fa6132019-05-07 19:37:21 -07001830 if (hp_removal_failed ||
1831 !IsValidFullPacketNumber(full_packet_number, transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001832 if (IsIetfStatelessResetPacket(*header)) {
1833 // This is a stateless reset packet.
1834 QuicIetfStatelessResetPacket packet(
1835 *header, header->possible_stateless_reset_token);
1836 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1837 return true;
1838 }
nharper55fa6132019-05-07 19:37:21 -07001839 if (hp_removal_failed) {
1840 set_detailed_error("Unable to decrypt header protection.");
1841 return RaiseError(QUIC_DECRYPTION_FAILURE);
1842 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001843 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1844 set_detailed_error("packet numbers cannot be 0.");
1845 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1846 }
1847 header->packet_number = QuicPacketNumber(full_packet_number);
1848 }
1849
1850 // A nonce should only present in SHLO from the server to the client when
1851 // using QUIC crypto.
1852 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1853 header->long_packet_type == ZERO_RTT_PROTECTED &&
1854 perspective_ == Perspective::IS_CLIENT &&
1855 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1856 if (!encrypted_reader->ReadBytes(
1857 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1858 last_nonce_.size())) {
1859 set_detailed_error("Unable to read nonce.");
1860 RecordDroppedPacketReason(
1861 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1862 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1863 }
1864
1865 header->nonce = &last_nonce_;
1866 } else {
1867 header->nonce = nullptr;
1868 }
1869
1870 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1871 set_detailed_error(
1872 "Visitor asked to stop processing of unauthenticated header.");
1873 return false;
1874 }
1875
1876 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001877 if (!version_.HasHeaderProtection()) {
1878 associated_data = GetAssociatedDataFromEncryptedPacket(
1879 version_.transport_version, packet,
1880 GetIncludedDestinationConnectionIdLength(*header),
1881 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1882 header->nonce != nullptr, header->packet_number_length,
1883 header->retry_token_length_length, header->retry_token.length(),
1884 header->length_length);
1885 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001886
1887 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001888 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001889 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001890 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001891 if (IsIetfStatelessResetPacket(*header)) {
1892 // This is a stateless reset packet.
1893 QuicIetfStatelessResetPacket packet(
1894 *header, header->possible_stateless_reset_token);
1895 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1896 return true;
1897 }
1898 set_detailed_error("Unable to decrypt payload.");
1899 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1900 return RaiseError(QUIC_DECRYPTION_FAILURE);
1901 }
1902 QuicDataReader reader(decrypted_buffer, decrypted_length);
1903
1904 // Update the largest packet number after we have decrypted the packet
1905 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001906 if (supports_multiple_packet_number_spaces_) {
1907 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1908 decrypted_level)]
1909 .UpdateMax(header->packet_number);
1910 } else {
1911 largest_packet_number_.UpdateMax(header->packet_number);
1912 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001913
1914 if (!visitor_->OnPacketHeader(*header)) {
1915 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1916 // The visitor suppresses further processing of the packet.
1917 return true;
1918 }
1919
dschinazie8d7fa72019-04-05 14:44:40 -07001920 if (packet.length() > kMaxIncomingPacketSize) {
1921 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001922 return RaiseError(QUIC_PACKET_TOO_LARGE);
1923 }
1924
1925 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001926 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001927 if (!ProcessIetfFrameData(&reader, *header)) {
1928 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1929 DCHECK_NE("", detailed_error_);
1930 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1931 << detailed_error_;
1932 return false;
1933 }
1934 } else {
1935 if (!ProcessFrameData(&reader, *header)) {
1936 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1937 DCHECK_NE("", detailed_error_);
1938 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1939 << detailed_error_;
1940 return false;
1941 }
1942 }
1943
1944 visitor_->OnPacketComplete();
1945 return true;
1946}
1947
1948bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1949 QuicPacketHeader* header,
1950 const QuicEncryptedPacket& packet,
1951 char* decrypted_buffer,
1952 size_t buffer_length) {
1953 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1954 DCHECK_NE("", detailed_error_);
1955 QUIC_DVLOG(1)
1956 << ENDPOINT
1957 << "Unable to process packet header. Stopping parsing. Error: "
1958 << detailed_error_;
1959 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1960 return false;
1961 }
1962
1963 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1964 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1965 version_.transport_version, packet,
1966 GetIncludedDestinationConnectionIdLength(*header),
1967 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1968 header->nonce != nullptr, header->packet_number_length,
1969 header->retry_token_length_length, header->retry_token.length(),
1970 header->length_length);
1971
1972 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001973 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001974 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001975 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001976 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1977 set_detailed_error("Unable to decrypt payload.");
1978 return RaiseError(QUIC_DECRYPTION_FAILURE);
1979 }
1980
1981 QuicDataReader reader(decrypted_buffer, decrypted_length);
1982
1983 // Update the largest packet number after we have decrypted the packet
1984 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001985 if (supports_multiple_packet_number_spaces_) {
1986 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1987 decrypted_level)]
1988 .UpdateMax(header->packet_number);
1989 } else {
1990 largest_packet_number_.UpdateMax(header->packet_number);
1991 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001992
1993 if (!visitor_->OnPacketHeader(*header)) {
1994 // The visitor suppresses further processing of the packet.
1995 return true;
1996 }
1997
dschinazie8d7fa72019-04-05 14:44:40 -07001998 if (packet.length() > kMaxIncomingPacketSize) {
1999 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002000 return RaiseError(QUIC_PACKET_TOO_LARGE);
2001 }
2002
2003 // Handle the payload.
2004 if (!ProcessFrameData(&reader, *header)) {
2005 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
2006 DCHECK_NE("", detailed_error_);
2007 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
2008 << detailed_error_;
2009 return false;
2010 }
2011
2012 visitor_->OnPacketComplete();
2013 return true;
2014}
2015
2016bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
2017 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04002018 QuicPublicResetPacket packet(
2019 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002020
2021 std::unique_ptr<CryptoHandshakeMessage> reset(
2022 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
2023 if (!reset.get()) {
2024 set_detailed_error("Unable to read reset message.");
2025 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2026 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2027 }
2028 if (reset->tag() != kPRST) {
2029 set_detailed_error("Incorrect message tag.");
2030 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2031 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2032 }
2033
2034 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
2035 set_detailed_error("Unable to read nonce proof.");
2036 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2037 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2038 }
2039 // TODO(satyamshekhar): validate nonce to protect against DoS.
2040
2041 QuicStringPiece address;
2042 if (reset->GetStringPiece(kCADR, &address)) {
2043 QuicSocketAddressCoder address_coder;
2044 if (address_coder.Decode(address.data(), address.length())) {
2045 packet.client_address =
2046 QuicSocketAddress(address_coder.ip(), address_coder.port());
2047 }
2048 }
2049
2050 QuicStringPiece endpoint_id;
2051 if (perspective_ == Perspective::IS_CLIENT &&
2052 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002053 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002054 packet.endpoint_id += '\0';
2055 }
2056
2057 visitor_->OnPublicResetPacket(packet);
2058 return true;
2059}
2060
2061bool QuicFramer::IsIetfStatelessResetPacket(
2062 const QuicPacketHeader& header) const {
2063 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2064 perspective_ != Perspective::IS_CLIENT)
2065 << "has_possible_stateless_reset_token can only be true at client side.";
2066 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2067 header.has_possible_stateless_reset_token &&
2068 visitor_->IsValidStatelessResetToken(
2069 header.possible_stateless_reset_token);
2070}
2071
2072bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2073 return encrypter_[level] != nullptr;
2074}
2075
2076bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2077 QuicDataWriter* writer,
2078 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002079 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002080 return AppendIetfPacketHeader(header, writer, length_field_offset);
2081 }
2082 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2083 uint8_t public_flags = 0;
2084 if (header.reset_flag) {
2085 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2086 }
2087 if (header.version_flag) {
2088 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2089 }
2090
2091 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2092 << kPublicHeaderSequenceNumberShift;
2093
2094 if (header.nonce != nullptr) {
2095 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2096 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2097 }
QUICHE team2252b702019-05-14 23:55:14 -04002098
dschinazi7b9278c2019-05-20 07:36:21 -07002099 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002100 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002101 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002102 GetServerConnectionIdIncludedAsSender(header, perspective_);
2103 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002104 GetClientConnectionIdIncludedAsSender(header, perspective_))
2105 << ENDPOINT << ParsedQuicVersionToString(version_)
2106 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002107
dschinazi7b9278c2019-05-20 07:36:21 -07002108 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002109 case CONNECTION_ID_ABSENT:
2110 if (!writer->WriteUInt8(public_flags |
2111 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2112 return false;
2113 }
2114 break;
2115 case CONNECTION_ID_PRESENT:
2116 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002117 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002118 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002119 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002120 << QuicVersionToString(transport_version());
2121
2122 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2123 if (perspective_ == Perspective::IS_CLIENT) {
2124 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2125 }
2126 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002127 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002128 return false;
2129 }
2130 break;
2131 }
dschinazi7b9278c2019-05-20 07:36:21 -07002132 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002133
2134 if (header.version_flag) {
2135 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2136 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002137 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002138 return false;
2139 }
2140
2141 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2142 << QuicVersionLabelToString(version_label) << "'";
2143 }
2144
2145 if (header.nonce != nullptr &&
2146 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2147 return false;
2148 }
2149
2150 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2151 writer)) {
2152 return false;
2153 }
2154
2155 return true;
2156}
2157
2158bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2159 QuicDataWriter* writer) {
2160 uint8_t type = 0;
fayangf36e29d2019-06-06 14:03:40 -07002161 if (transport_version() > QUIC_VERSION_44) {
2162 if (header.version_flag) {
2163 type = static_cast<uint8_t>(
2164 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2165 LongHeaderTypeToOnWireValue(transport_version(),
2166 header.long_packet_type) |
2167 PacketNumberLengthToOnWireValue(transport_version(),
2168 header.packet_number_length));
2169 } else {
2170 type = static_cast<uint8_t>(
2171 FLAGS_FIXED_BIT |
2172 PacketNumberLengthToOnWireValue(transport_version(),
2173 header.packet_number_length));
2174 }
2175 return writer->WriteUInt8(type);
2176 }
2177
QUICHE teama6ef0a62019-03-07 20:34:33 -05002178 if (header.version_flag) {
2179 type = static_cast<uint8_t>(
fayangf36e29d2019-06-06 14:03:40 -07002180 FLAGS_LONG_HEADER | LongHeaderTypeToOnWireValue(
2181 transport_version(), header.long_packet_type));
2182 DCHECK_EQ(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002183 } else {
fayangf36e29d2019-06-06 14:03:40 -07002184 type |= FLAGS_SHORT_HEADER_RESERVED_1;
2185 type |= FLAGS_SHORT_HEADER_RESERVED_2;
2186 DCHECK_GE(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
2187 type |= PacketNumberLengthToOnWireValue(transport_version(),
2188 header.packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002189 }
2190 return writer->WriteUInt8(type);
2191}
2192
2193bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2194 QuicDataWriter* writer,
2195 size_t* length_field_offset) {
2196 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002197 QuicConnectionId server_connection_id =
2198 GetServerConnectionIdAsSender(header, perspective_);
2199 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2200 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002201 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002202 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002203 << QuicVersionToString(transport_version());
2204 if (!AppendIetfHeaderTypeByte(header, writer)) {
2205 return false;
2206 }
2207
2208 if (header.version_flag) {
2209 // Append version for long header.
2210 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002211 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002212 return false;
2213 }
2214 }
2215
2216 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002217 if (!AppendIetfConnectionIds(
2218 header.version_flag,
2219 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2220 ? header.destination_connection_id
2221 : EmptyQuicConnectionId(),
2222 header.source_connection_id_included != CONNECTION_ID_ABSENT
2223 ? header.source_connection_id
2224 : EmptyQuicConnectionId(),
2225 writer)) {
2226 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002227 }
dschinazi1f485a12019-05-13 11:57:01 -07002228
dschinazi7b9278c2019-05-20 07:36:21 -07002229 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002230 if (version_.SupportsClientConnectionIds()) {
2231 last_serialized_client_connection_id_ =
2232 GetClientConnectionIdAsSender(header, perspective_);
2233 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002234
2235 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2236 header.version_flag) {
2237 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002238 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2239 header.retry_token_length_length)
2240 << ENDPOINT << ParsedQuicVersionToString(version_)
2241 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002242 // Write retry token length.
2243 if (!writer->WriteVarInt62(header.retry_token.length(),
2244 header.retry_token_length_length)) {
2245 return false;
2246 }
2247 // Write retry token.
2248 if (!header.retry_token.empty() &&
2249 !writer->WriteStringPiece(header.retry_token)) {
2250 return false;
2251 }
2252 }
2253 if (length_field_offset != nullptr) {
2254 *length_field_offset = writer->length();
2255 }
2256 // Add fake length to reserve two bytes to add length in later.
2257 writer->WriteVarInt62(256);
2258 } else if (length_field_offset != nullptr) {
2259 *length_field_offset = 0;
2260 }
2261
2262 // Append packet number.
2263 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2264 writer)) {
2265 return false;
2266 }
nharper55fa6132019-05-07 19:37:21 -07002267 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002268
2269 if (!header.version_flag) {
2270 return true;
2271 }
2272
2273 if (header.nonce != nullptr) {
2274 DCHECK(header.version_flag);
2275 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2276 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2277 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2278 return false;
2279 }
2280 }
2281
2282 return true;
2283}
2284
2285const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2286 uint32_t time_delta_us) {
2287 // The new time_delta might have wrapped to the next epoch, or it
2288 // might have reverse wrapped to the previous epoch, or it might
2289 // remain in the same epoch. Select the time closest to the previous
2290 // time.
2291 //
2292 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2293 // microseconds.
2294 const uint64_t epoch_delta = UINT64_C(1) << 32;
2295 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2296 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2297 uint64_t prev_epoch = epoch - epoch_delta;
2298 uint64_t next_epoch = epoch + epoch_delta;
2299
2300 uint64_t time = ClosestTo(
2301 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2302 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2303 next_epoch + time_delta_us));
2304
2305 return QuicTime::Delta::FromMicroseconds(time);
2306}
2307
2308uint64_t QuicFramer::CalculatePacketNumberFromWire(
2309 QuicPacketNumberLength packet_number_length,
2310 QuicPacketNumber base_packet_number,
2311 uint64_t packet_number) const {
2312 // The new packet number might have wrapped to the next epoch, or
2313 // it might have reverse wrapped to the previous epoch, or it might
2314 // remain in the same epoch. Select the packet number closest to the
2315 // next expected packet number, the previous packet number plus 1.
2316
2317 // epoch_delta is the delta between epochs the packet number was serialized
2318 // with, so the correct value is likely the same epoch as the last sequence
2319 // number or an adjacent epoch.
2320 if (!base_packet_number.IsInitialized()) {
2321 return packet_number;
2322 }
2323 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2324 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2325 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2326 uint64_t prev_epoch = epoch - epoch_delta;
2327 uint64_t next_epoch = epoch + epoch_delta;
2328
2329 return ClosestTo(next_packet_number, epoch + packet_number,
2330 ClosestTo(next_packet_number, prev_epoch + packet_number,
2331 next_epoch + packet_number));
2332}
2333
2334bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2335 bool packet_has_ietf_packet_header,
2336 QuicPacketHeader* header) {
2337 if (packet_has_ietf_packet_header) {
2338 return ProcessIetfPacketHeader(reader, header);
2339 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002340 uint8_t public_flags;
2341 if (!reader->ReadBytes(&public_flags, 1)) {
2342 set_detailed_error("Unable to read public flags.");
2343 return false;
2344 }
2345
2346 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2347 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2348
2349 if (validate_flags_ && !header->version_flag &&
2350 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2351 set_detailed_error("Illegal public flags value.");
2352 return false;
2353 }
2354
2355 if (header->reset_flag && header->version_flag) {
2356 set_detailed_error("Got version flag in reset packet");
2357 return false;
2358 }
2359
QUICHE team2252b702019-05-14 23:55:14 -04002360 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2361 QuicConnectionIdIncluded* header_connection_id_included =
2362 &header->destination_connection_id_included;
2363 if (perspective_ == Perspective::IS_CLIENT &&
2364 GetQuicRestartFlag(quic_do_not_override_connection_id)) {
2365 header_connection_id = &header->source_connection_id;
2366 header_connection_id_included = &header->source_connection_id_included;
2367 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002368 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2369 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002370 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002371 kQuicDefaultConnectionIdLength)) {
2372 set_detailed_error("Unable to read ConnectionId.");
2373 return false;
2374 }
QUICHE team2252b702019-05-14 23:55:14 -04002375 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002376 break;
2377 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002378 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002379 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002380 break;
2381 }
2382
2383 header->packet_number_length = ReadSequenceNumberLength(
2384 public_flags >> kPublicHeaderSequenceNumberShift);
2385
2386 // Read the version only if the packet is from the client.
2387 // version flag from the server means version negotiation packet.
2388 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2389 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002390 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002391 set_detailed_error("Unable to read protocol version.");
2392 return false;
2393 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002394 // If the version from the new packet is the same as the version of this
2395 // framer, then the public flags should be set to something we understand.
2396 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002397 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2398 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2399 set_detailed_error("Illegal public flags value.");
2400 return false;
2401 }
2402 header->version = version;
2403 }
2404
2405 // A nonce should only be present in packets from the server to the client,
2406 // which are neither version negotiation nor public reset packets.
2407 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2408 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2409 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2410 // The nonce flag from a client is ignored and is assumed to be an older
2411 // client indicating an eight-byte connection ID.
2412 perspective_ == Perspective::IS_CLIENT) {
2413 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2414 last_nonce_.size())) {
2415 set_detailed_error("Unable to read nonce.");
2416 return false;
2417 }
2418 header->nonce = &last_nonce_;
2419 } else {
2420 header->nonce = nullptr;
2421 }
2422
2423 return true;
2424}
2425
2426// static
2427QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -07002428 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002429 QuicPacketNumber packet_number) {
2430 DCHECK(packet_number.IsInitialized());
2431 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2432 return PACKET_1BYTE_PACKET_NUMBER;
2433 } else if (packet_number <
2434 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2435 return PACKET_2BYTE_PACKET_NUMBER;
2436 } else if (packet_number <
2437 QuicPacketNumber(UINT64_C(1)
2438 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2439 return PACKET_4BYTE_PACKET_NUMBER;
2440 } else {
2441 return PACKET_6BYTE_PACKET_NUMBER;
2442 }
2443}
2444
2445// static
2446uint8_t QuicFramer::GetPacketNumberFlags(
2447 QuicPacketNumberLength packet_number_length) {
2448 switch (packet_number_length) {
2449 case PACKET_1BYTE_PACKET_NUMBER:
2450 return PACKET_FLAGS_1BYTE_PACKET;
2451 case PACKET_2BYTE_PACKET_NUMBER:
2452 return PACKET_FLAGS_2BYTE_PACKET;
2453 case PACKET_4BYTE_PACKET_NUMBER:
2454 return PACKET_FLAGS_4BYTE_PACKET;
2455 case PACKET_6BYTE_PACKET_NUMBER:
2456 case PACKET_8BYTE_PACKET_NUMBER:
2457 return PACKET_FLAGS_8BYTE_PACKET;
2458 default:
2459 QUIC_BUG << "Unreachable case statement.";
2460 return PACKET_FLAGS_8BYTE_PACKET;
2461 }
2462}
2463
2464// static
2465QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2466 const QuicAckFrame& frame) {
2467 AckFrameInfo new_ack_info;
2468 if (frame.packets.Empty()) {
2469 return new_ack_info;
2470 }
2471 // The first block is the last interval. It isn't encoded with the gap-length
2472 // encoding, so skip it.
2473 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2474 auto itr = frame.packets.rbegin();
2475 QuicPacketNumber previous_start = itr->min();
2476 new_ack_info.max_block_length = PacketNumberIntervalLength(*itr);
2477 ++itr;
2478
2479 // Don't do any more work after getting information for 256 ACK blocks; any
2480 // more can't be encoded anyway.
2481 for (; itr != frame.packets.rend() &&
2482 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2483 previous_start = itr->min(), ++itr) {
2484 const auto& interval = *itr;
2485 const QuicPacketCount total_gap = previous_start - interval.max();
2486 new_ack_info.num_ack_blocks +=
2487 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2488 std::numeric_limits<uint8_t>::max();
2489 new_ack_info.max_block_length = std::max(
2490 new_ack_info.max_block_length, PacketNumberIntervalLength(interval));
2491 }
2492 return new_ack_info;
2493}
2494
2495bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2496 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002497 QuicPacketNumber base_packet_number;
2498 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002499 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2500 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2501 set_detailed_error("Unable to determine packet number space.");
2502 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2503 }
2504 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002505 } else {
2506 base_packet_number = largest_packet_number_;
2507 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002508 uint64_t full_packet_number;
2509 if (!ProcessAndCalculatePacketNumber(
2510 encrypted_reader, header->packet_number_length, base_packet_number,
2511 &full_packet_number)) {
2512 set_detailed_error("Unable to read packet number.");
2513 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2514 }
2515
2516 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2517 set_detailed_error("packet numbers cannot be 0.");
2518 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2519 }
2520 header->packet_number = QuicPacketNumber(full_packet_number);
2521
2522 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2523 set_detailed_error(
2524 "Visitor asked to stop processing of unauthenticated header.");
2525 return false;
2526 }
nharper3f283562019-05-02 16:37:12 -07002527 // The function we are in is called because the framer believes that it is
2528 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2529 // type. Usually, the framer makes that decision based on the framer's
2530 // version, but when the framer is used with Perspective::IS_SERVER, then
2531 // before version negotiation is complete (specifically, before
2532 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2533 // the type byte of the packet.
2534 //
2535 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2536 // to use the IETF packet header type. If that's the case and we're in this
2537 // function, then the packet received is invalid: the framer was expecting an
2538 // IETF packet header and didn't get one.
2539 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002540 set_detailed_error("Invalid public header type for expected version.");
2541 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2542 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002543 return true;
2544}
2545
2546bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2547 QuicPacketHeader* header) {
2548 uint8_t type;
2549 if (!reader->ReadBytes(&type, 1)) {
2550 set_detailed_error("Unable to read type.");
2551 return false;
2552 }
dschinazi244f6dc2019-05-06 15:45:16 -07002553 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002554 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002555 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002556 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2557 // Version is always present in long headers.
2558 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002559 // In versions that do not support client connection IDs, we mark the
2560 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002561 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002562 (perspective_ == Perspective::IS_SERVER ||
2563 version_.SupportsClientConnectionIds())
2564 ? CONNECTION_ID_PRESENT
2565 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002566 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002567 (perspective_ == Perspective::IS_CLIENT ||
2568 version_.SupportsClientConnectionIds())
2569 ? CONNECTION_ID_PRESENT
2570 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002571 // Read version tag.
2572 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002573 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002574 set_detailed_error("Unable to read protocol version.");
2575 return false;
2576 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002577 if (!version_label) {
2578 // Version label is 0 indicating this is a version negotiation packet.
2579 header->long_packet_type = VERSION_NEGOTIATION;
2580 } else {
2581 header->version = ParseQuicVersionLabel(version_label);
2582 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayangf36e29d2019-06-06 14:03:40 -07002583 if (header->version.transport_version > QUIC_VERSION_44 &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05002584 !(type & FLAGS_FIXED_BIT)) {
2585 set_detailed_error("Fixed bit is 0 in long header.");
2586 return false;
2587 }
2588 if (!GetLongHeaderType(header->version.transport_version, type,
2589 &header->long_packet_type)) {
2590 set_detailed_error("Illegal long header type value.");
2591 return false;
2592 }
dschinazi244f6dc2019-05-06 15:45:16 -07002593 if (header->long_packet_type == RETRY) {
2594 if (!version().SupportsRetry()) {
2595 set_detailed_error("RETRY not supported in this version.");
2596 return false;
2597 }
2598 if (perspective_ == Perspective::IS_SERVER) {
2599 set_detailed_error("Client-initiated RETRY is invalid.");
2600 return false;
2601 }
nharper55fa6132019-05-07 19:37:21 -07002602 } else if (!header->version.HasHeaderProtection()) {
dschinazi244f6dc2019-05-06 15:45:16 -07002603 header->packet_number_length = GetLongHeaderPacketNumberLength(
2604 header->version.transport_version, type);
nharper2ceb97c2019-04-19 11:38:59 -07002605 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002606 }
2607 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002608
2609 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2610 << QuicUtils::QuicLongHeaderTypetoString(
2611 header->long_packet_type);
2612 return true;
2613 }
2614
2615 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2616 // Version is not present in short headers.
2617 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002618 // In versions that do not support client connection IDs, the client will not
2619 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002620 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002621 (perspective_ == Perspective::IS_SERVER ||
2622 version_.SupportsClientConnectionIds())
2623 ? CONNECTION_ID_PRESENT
2624 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002625 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayangf36e29d2019-06-06 14:03:40 -07002626 if (infer_packet_header_type_from_version_ &&
2627 transport_version() > QUIC_VERSION_44 && !(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002628 set_detailed_error("Fixed bit is 0 in short header.");
2629 return false;
2630 }
nharper55fa6132019-05-07 19:37:21 -07002631 if (!header->version.HasHeaderProtection() &&
2632 !GetShortHeaderPacketNumberLength(transport_version(), type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002633 infer_packet_header_type_from_version_,
2634 &header->packet_number_length)) {
2635 set_detailed_error("Illegal short header type value.");
2636 return false;
2637 }
2638 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2639 return true;
2640}
2641
fayang40315542019-05-09 09:19:09 -07002642// static
2643bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2644 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002645 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002646 return false;
2647 }
fayang40315542019-05-09 09:19:09 -07002648 return true;
2649}
2650
2651// static
fayangccbab732019-05-13 10:11:25 -07002652bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2653 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002654 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002655 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002656 bool should_update_expected_server_connection_id_length,
2657 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002658 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002659 uint8_t* source_connection_id_length,
2660 std::string* detailed_error) {
2661 uint8_t connection_id_lengths_byte;
2662 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2663 *detailed_error = "Unable to read ConnectionId length.";
2664 return false;
2665 }
fayang40315542019-05-09 09:19:09 -07002666 uint8_t dcil =
2667 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2668 if (dcil != 0) {
2669 dcil += kConnectionIdLengthAdjustment;
2670 }
fayang40315542019-05-09 09:19:09 -07002671 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2672 if (scil != 0) {
2673 scil += kConnectionIdLengthAdjustment;
2674 }
dschinazi334f0232019-05-29 16:08:53 -07002675 if (should_update_expected_server_connection_id_length) {
2676 uint8_t server_connection_id_length =
2677 perspective == Perspective::IS_SERVER ? dcil : scil;
2678 if (*expected_server_connection_id_length != server_connection_id_length) {
2679 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2680 << static_cast<int>(*expected_server_connection_id_length)
2681 << " -> " << static_cast<int>(server_connection_id_length);
2682 *expected_server_connection_id_length = server_connection_id_length;
2683 }
2684 }
dschinazi8ff74822019-05-28 16:37:20 -07002685 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002686 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002687 scil != *source_connection_id_length) &&
fayang40315542019-05-09 09:19:09 -07002688 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2689 version.transport_version)) {
2690 // TODO(dschinazi): use the framer's version once the
2691 // OnProtocolVersionMismatch call is moved to before this is run.
2692 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2693 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002694 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002695 return false;
2696 }
2697 *destination_connection_id_length = dcil;
2698 *source_connection_id_length = scil;
2699 return true;
2700}
2701
QUICHE teama6ef0a62019-03-07 20:34:33 -05002702bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2703 QuicPacketHeader* header) {
2704 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2705 return false;
2706 }
2707
2708 uint8_t destination_connection_id_length =
2709 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002710 ? (perspective_ == Perspective::IS_SERVER
2711 ? expected_server_connection_id_length_
2712 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002713 : 0;
2714 uint8_t source_connection_id_length =
2715 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002716 ? (perspective_ == Perspective::IS_CLIENT
2717 ? expected_server_connection_id_length_
2718 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002719 : 0;
2720 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002721 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002722 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002723 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002724 &expected_server_connection_id_length_,
2725 &destination_connection_id_length, &source_connection_id_length,
2726 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002727 return false;
2728 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002729 }
2730
QUICHE team0131a5b2019-03-20 15:23:27 -07002731 DCHECK_LE(destination_connection_id_length, kQuicMaxConnectionIdLength);
2732 DCHECK_LE(source_connection_id_length, kQuicMaxConnectionIdLength);
2733
QUICHE teama6ef0a62019-03-07 20:34:33 -05002734 // Read connection ID.
2735 if (!reader->ReadConnectionId(&header->destination_connection_id,
2736 destination_connection_id_length)) {
2737 set_detailed_error("Unable to read Destination ConnectionId.");
2738 return false;
2739 }
2740
2741 if (!reader->ReadConnectionId(&header->source_connection_id,
2742 source_connection_id_length)) {
2743 set_detailed_error("Unable to read Source ConnectionId.");
2744 return false;
2745 }
2746
QUICHE team2252b702019-05-14 23:55:14 -04002747 if (!GetQuicRestartFlag(quic_do_not_override_connection_id)) {
2748 if (header->source_connection_id_included == CONNECTION_ID_PRESENT) {
dschinazi7d066ca2019-05-15 17:59:49 -07002749 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2750 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, header->form);
2751 if (!header->destination_connection_id.IsEmpty()) {
2752 set_detailed_error("Client connection ID not supported yet.");
2753 return false;
2754 }
QUICHE team2252b702019-05-14 23:55:14 -04002755 // Set destination connection ID to source connection ID.
QUICHE team2252b702019-05-14 23:55:14 -04002756 header->destination_connection_id = header->source_connection_id;
2757 } else if (header->destination_connection_id_included ==
2758 CONNECTION_ID_ABSENT) {
dschinazi7b9278c2019-05-20 07:36:21 -07002759 header->destination_connection_id = last_serialized_server_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002760 }
2761 } else {
dschinazib9bdd052019-06-05 03:06:33 -07002762 QUIC_RESTART_FLAG_COUNT_N(quic_do_not_override_connection_id, 5, 7);
QUICHE team2252b702019-05-14 23:55:14 -04002763 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
dschinazi346b7ce2019-06-05 01:38:18 -07002764 if (!header->source_connection_id.IsEmpty()) {
2765 DCHECK(!version_.SupportsClientConnectionIds());
2766 set_detailed_error(
2767 "Client connection ID not supported in this version.");
2768 return false;
2769 }
2770 if (perspective_ == Perspective::IS_CLIENT) {
2771 header->source_connection_id = last_serialized_server_connection_id_;
2772 } else {
2773 header->source_connection_id = last_serialized_client_connection_id_;
2774 }
QUICHE team2252b702019-05-14 23:55:14 -04002775 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002776 }
2777
2778 return true;
2779}
2780
2781bool QuicFramer::ProcessAndCalculatePacketNumber(
2782 QuicDataReader* reader,
2783 QuicPacketNumberLength packet_number_length,
2784 QuicPacketNumber base_packet_number,
2785 uint64_t* packet_number) {
2786 uint64_t wire_packet_number;
2787 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2788 return false;
2789 }
2790
2791 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2792 // in case the first guess is incorrect.
2793 *packet_number = CalculatePacketNumberFromWire(
2794 packet_number_length, base_packet_number, wire_packet_number);
2795 return true;
2796}
2797
2798bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2799 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002800 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2801 << "IETF QUIC Framing negotiated but attempting to process frames as "
2802 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002803 if (reader->IsDoneReading()) {
2804 set_detailed_error("Packet has no frames.");
2805 return RaiseError(QUIC_MISSING_PAYLOAD);
2806 }
dschinazi118934b2019-06-13 18:09:08 -07002807 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002808 while (!reader->IsDoneReading()) {
2809 uint8_t frame_type;
2810 if (!reader->ReadBytes(&frame_type, 1)) {
2811 set_detailed_error("Unable to read frame type.");
2812 return RaiseError(QUIC_INVALID_FRAME_DATA);
2813 }
fayangf36e29d2019-06-06 14:03:40 -07002814 const uint8_t special_mask = transport_version() <= QUIC_VERSION_44
QUICHE teama6ef0a62019-03-07 20:34:33 -05002815 ? kQuicFrameTypeBrokenMask
2816 : kQuicFrameTypeSpecialMask;
2817 if (frame_type & special_mask) {
2818 // Stream Frame
2819 if (frame_type & kQuicFrameTypeStreamMask) {
2820 QuicStreamFrame frame;
2821 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2822 return RaiseError(QUIC_INVALID_STREAM_DATA);
2823 }
dschinazi118934b2019-06-13 18:09:08 -07002824 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002825 if (!visitor_->OnStreamFrame(frame)) {
2826 QUIC_DVLOG(1) << ENDPOINT
2827 << "Visitor asked to stop further processing.";
2828 // Returning true since there was no parsing error.
2829 return true;
2830 }
2831 continue;
2832 }
2833
2834 // Ack Frame
2835 if (frame_type & kQuicFrameTypeAckMask) {
2836 if (!ProcessAckFrame(reader, frame_type)) {
2837 return RaiseError(QUIC_INVALID_ACK_DATA);
2838 }
dschinazi118934b2019-06-13 18:09:08 -07002839 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002840 continue;
2841 }
2842
2843 // This was a special frame type that did not match any
2844 // of the known ones. Error.
2845 set_detailed_error("Illegal frame type.");
2846 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2847 << static_cast<int>(frame_type);
2848 return RaiseError(QUIC_INVALID_FRAME_DATA);
2849 }
2850
2851 switch (frame_type) {
2852 case PADDING_FRAME: {
2853 QuicPaddingFrame frame;
2854 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002855 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002856 if (!visitor_->OnPaddingFrame(frame)) {
2857 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2858 // Returning true since there was no parsing error.
2859 return true;
2860 }
2861 continue;
2862 }
2863
2864 case RST_STREAM_FRAME: {
2865 QuicRstStreamFrame frame;
2866 if (!ProcessRstStreamFrame(reader, &frame)) {
2867 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2868 }
dschinazi118934b2019-06-13 18:09:08 -07002869 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002870 if (!visitor_->OnRstStreamFrame(frame)) {
2871 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2872 // Returning true since there was no parsing error.
2873 return true;
2874 }
2875 continue;
2876 }
2877
2878 case CONNECTION_CLOSE_FRAME: {
2879 QuicConnectionCloseFrame frame;
2880 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2881 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2882 }
2883
dschinazi118934b2019-06-13 18:09:08 -07002884 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2885 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002886 if (!visitor_->OnConnectionCloseFrame(frame)) {
2887 QUIC_DVLOG(1) << ENDPOINT
2888 << "Visitor asked to stop further processing.";
2889 // Returning true since there was no parsing error.
2890 return true;
2891 }
2892 continue;
2893 }
2894
2895 case GOAWAY_FRAME: {
2896 QuicGoAwayFrame goaway_frame;
2897 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2898 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2899 }
dschinazi118934b2019-06-13 18:09:08 -07002900 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2901 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002902 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2903 QUIC_DVLOG(1) << ENDPOINT
2904 << "Visitor asked to stop further processing.";
2905 // Returning true since there was no parsing error.
2906 return true;
2907 }
2908 continue;
2909 }
2910
2911 case WINDOW_UPDATE_FRAME: {
2912 QuicWindowUpdateFrame window_update_frame;
2913 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2914 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2915 }
dschinazi118934b2019-06-13 18:09:08 -07002916 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2917 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002918 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2919 QUIC_DVLOG(1) << ENDPOINT
2920 << "Visitor asked to stop further processing.";
2921 // Returning true since there was no parsing error.
2922 return true;
2923 }
2924 continue;
2925 }
2926
2927 case BLOCKED_FRAME: {
2928 QuicBlockedFrame blocked_frame;
2929 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2930 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2931 }
dschinazi118934b2019-06-13 18:09:08 -07002932 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2933 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002934 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2935 QUIC_DVLOG(1) << ENDPOINT
2936 << "Visitor asked to stop further processing.";
2937 // Returning true since there was no parsing error.
2938 return true;
2939 }
2940 continue;
2941 }
2942
2943 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002944 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayangf36e29d2019-06-06 14:03:40 -07002945 version_.transport_version >= QUIC_VERSION_44) {
ianswett97b690b2019-05-02 15:12:43 -07002946 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2947 set_detailed_error("STOP WAITING not supported in version 44+.");
2948 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2949 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002950 QuicStopWaitingFrame stop_waiting_frame;
2951 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2952 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2953 }
dschinazi118934b2019-06-13 18:09:08 -07002954 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2955 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002956 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2957 QUIC_DVLOG(1) << ENDPOINT
2958 << "Visitor asked to stop further processing.";
2959 // Returning true since there was no parsing error.
2960 return true;
2961 }
2962 continue;
2963 }
2964 case PING_FRAME: {
2965 // Ping has no payload.
2966 QuicPingFrame ping_frame;
2967 if (!visitor_->OnPingFrame(ping_frame)) {
2968 QUIC_DVLOG(1) << ENDPOINT
2969 << "Visitor asked to stop further processing.";
2970 // Returning true since there was no parsing error.
2971 return true;
2972 }
dschinazi118934b2019-06-13 18:09:08 -07002973 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002974 continue;
2975 }
2976 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2977 QUIC_FALLTHROUGH_INTENDED;
2978 case IETF_EXTENSION_MESSAGE: {
2979 QuicMessageFrame message_frame;
2980 if (!ProcessMessageFrame(reader,
2981 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2982 &message_frame)) {
2983 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2984 }
dschinazi118934b2019-06-13 18:09:08 -07002985 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
2986 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002987 if (!visitor_->OnMessageFrame(message_frame)) {
2988 QUIC_DVLOG(1) << ENDPOINT
2989 << "Visitor asked to stop further processing.";
2990 // Returning true since there was no parsing error.
2991 return true;
2992 }
2993 break;
2994 }
2995 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07002996 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002997 set_detailed_error("Illegal frame type.");
2998 return RaiseError(QUIC_INVALID_FRAME_DATA);
2999 }
3000 QuicCryptoFrame frame;
3001 if (!ProcessCryptoFrame(reader, &frame)) {
3002 return RaiseError(QUIC_INVALID_FRAME_DATA);
3003 }
dschinazi118934b2019-06-13 18:09:08 -07003004 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003005 if (!visitor_->OnCryptoFrame(frame)) {
3006 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3007 // Returning true since there was no parsing error.
3008 return true;
3009 }
3010 break;
3011 }
3012
3013 default:
3014 set_detailed_error("Illegal frame type.");
3015 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
3016 << static_cast<int>(frame_type);
3017 return RaiseError(QUIC_INVALID_FRAME_DATA);
3018 }
3019 }
3020
3021 return true;
3022}
3023
3024bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3025 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07003026 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3027 << "Attempt to process frames as IETF frames but version ("
3028 << version_.transport_version << ") does not support IETF Framing.";
3029
QUICHE teama6ef0a62019-03-07 20:34:33 -05003030 if (reader->IsDoneReading()) {
3031 set_detailed_error("Packet has no frames.");
3032 return RaiseError(QUIC_MISSING_PAYLOAD);
3033 }
dschinazi118934b2019-06-13 18:09:08 -07003034
3035 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003036 while (!reader->IsDoneReading()) {
3037 uint64_t frame_type;
3038 // Will be the number of bytes into which frame_type was encoded.
3039 size_t encoded_bytes = reader->BytesRemaining();
3040 if (!reader->ReadVarInt62(&frame_type)) {
3041 set_detailed_error("Unable to read frame type.");
3042 return RaiseError(QUIC_INVALID_FRAME_DATA);
3043 }
3044
3045 // Is now the number of bytes into which the frame type was encoded.
3046 encoded_bytes -= reader->BytesRemaining();
3047
3048 // Check that the frame type is minimally encoded.
3049 if (encoded_bytes !=
3050 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3051 // The frame type was not minimally encoded.
3052 set_detailed_error("Frame type not minimally encoded.");
3053 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3054 }
3055
3056 if (IS_IETF_STREAM_FRAME(frame_type)) {
3057 QuicStreamFrame frame;
3058 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3059 return RaiseError(QUIC_INVALID_STREAM_DATA);
3060 }
dschinazi118934b2019-06-13 18:09:08 -07003061 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003062 if (!visitor_->OnStreamFrame(frame)) {
3063 QUIC_DVLOG(1) << ENDPOINT
3064 << "Visitor asked to stop further processing.";
3065 // Returning true since there was no parsing error.
3066 return true;
3067 }
3068 } else {
3069 switch (frame_type) {
3070 case IETF_PADDING: {
3071 QuicPaddingFrame frame;
3072 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003073 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3074 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003075 if (!visitor_->OnPaddingFrame(frame)) {
3076 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3077 // Returning true since there was no parsing error.
3078 return true;
3079 }
3080 break;
3081 }
3082 case IETF_RST_STREAM: {
3083 QuicRstStreamFrame frame;
3084 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3085 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3086 }
dschinazi118934b2019-06-13 18:09:08 -07003087 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3088 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003089 if (!visitor_->OnRstStreamFrame(frame)) {
3090 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3091 // Returning true since there was no parsing error.
3092 return true;
3093 }
3094 break;
3095 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003096 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003097 case IETF_CONNECTION_CLOSE: {
3098 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003099 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003100 reader,
3101 (frame_type == IETF_CONNECTION_CLOSE)
3102 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3103 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3104 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003105 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3106 }
dschinazi118934b2019-06-13 18:09:08 -07003107 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3108 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003109 if (!visitor_->OnConnectionCloseFrame(frame)) {
3110 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3111 // Returning true since there was no parsing error.
3112 return true;
3113 }
3114 break;
3115 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003116 case IETF_MAX_DATA: {
3117 QuicWindowUpdateFrame frame;
3118 if (!ProcessMaxDataFrame(reader, &frame)) {
3119 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3120 }
3121 // TODO(fkastenholz): Or should we create a new visitor function,
3122 // OnMaxDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003123 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3124 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003125 if (!visitor_->OnWindowUpdateFrame(frame)) {
3126 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3127 // Returning true since there was no parsing error.
3128 return true;
3129 }
3130 break;
3131 }
3132 case IETF_MAX_STREAM_DATA: {
3133 QuicWindowUpdateFrame frame;
3134 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3135 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3136 }
3137 // TODO(fkastenholz): Or should we create a new visitor function,
3138 // OnMaxStreamDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003139 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3140 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003141 if (!visitor_->OnWindowUpdateFrame(frame)) {
3142 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3143 // Returning true since there was no parsing error.
3144 return true;
3145 }
3146 break;
3147 }
3148 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3149 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003150 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003151 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003152 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003153 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003154 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003155 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3156 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003157 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003158 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_PING: {
3165 // Ping has no payload.
3166 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003167 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3168 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003169 if (!visitor_->OnPingFrame(ping_frame)) {
3170 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3171 // Returning true since there was no parsing error.
3172 return true;
3173 }
3174 break;
3175 }
3176 case IETF_BLOCKED: {
3177 QuicBlockedFrame frame;
3178 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3179 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3180 }
dschinazi118934b2019-06-13 18:09:08 -07003181 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3182 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003183 if (!visitor_->OnBlockedFrame(frame)) {
3184 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3185 // Returning true since there was no parsing error.
3186 return true;
3187 }
3188 break;
3189 }
3190 case IETF_STREAM_BLOCKED: {
3191 QuicBlockedFrame frame;
3192 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3193 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3194 }
dschinazi118934b2019-06-13 18:09:08 -07003195 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3196 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003197 if (!visitor_->OnBlockedFrame(frame)) {
3198 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3199 // Returning true since there was no parsing error.
3200 return true;
3201 }
3202 break;
3203 }
3204 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3205 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003206 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003207 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003208 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003209 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003210 QUIC_CODE_COUNT_N(quic_streams_blocked_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003211 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3212 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003213 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003214 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3215 // Returning true since there was no parsing error.
3216 return true;
3217 }
3218 break;
3219 }
3220 case IETF_NEW_CONNECTION_ID: {
3221 QuicNewConnectionIdFrame frame;
3222 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3223 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3224 }
dschinazi118934b2019-06-13 18:09:08 -07003225 QUIC_DVLOG(2) << ENDPOINT
3226 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003227 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3228 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3229 // Returning true since there was no parsing error.
3230 return true;
3231 }
3232 break;
3233 }
3234 case IETF_RETIRE_CONNECTION_ID: {
3235 QuicRetireConnectionIdFrame frame;
3236 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3237 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3238 }
dschinazi118934b2019-06-13 18:09:08 -07003239 QUIC_DVLOG(2) << ENDPOINT
3240 << "Processing IETF retire connection ID frame "
3241 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003242 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3243 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3244 // Returning true since there was no parsing error.
3245 return true;
3246 }
3247 break;
3248 }
3249 case IETF_NEW_TOKEN: {
3250 QuicNewTokenFrame frame;
3251 if (!ProcessNewTokenFrame(reader, &frame)) {
3252 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3253 }
dschinazi118934b2019-06-13 18:09:08 -07003254 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3255 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003256 if (!visitor_->OnNewTokenFrame(frame)) {
3257 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3258 // Returning true since there was no parsing error.
3259 return true;
3260 }
3261 break;
3262 }
3263 case IETF_STOP_SENDING: {
3264 QuicStopSendingFrame frame;
3265 if (!ProcessStopSendingFrame(reader, &frame)) {
3266 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3267 }
dschinazi118934b2019-06-13 18:09:08 -07003268 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3269 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003270 if (!visitor_->OnStopSendingFrame(frame)) {
3271 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3272 // Returning true since there was no parsing error.
3273 return true;
3274 }
3275 break;
3276 }
3277 case IETF_ACK_ECN:
3278 case IETF_ACK: {
3279 QuicAckFrame frame;
3280 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3281 return RaiseError(QUIC_INVALID_ACK_DATA);
3282 }
dschinazi118934b2019-06-13 18:09:08 -07003283 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003284 break;
3285 }
3286 case IETF_PATH_CHALLENGE: {
3287 QuicPathChallengeFrame frame;
3288 if (!ProcessPathChallengeFrame(reader, &frame)) {
3289 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3290 }
dschinazi118934b2019-06-13 18:09:08 -07003291 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3292 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003293 if (!visitor_->OnPathChallengeFrame(frame)) {
3294 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3295 // Returning true since there was no parsing error.
3296 return true;
3297 }
3298 break;
3299 }
3300 case IETF_PATH_RESPONSE: {
3301 QuicPathResponseFrame frame;
3302 if (!ProcessPathResponseFrame(reader, &frame)) {
3303 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3304 }
dschinazi118934b2019-06-13 18:09:08 -07003305 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3306 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003307 if (!visitor_->OnPathResponseFrame(frame)) {
3308 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3309 // Returning true since there was no parsing error.
3310 return true;
3311 }
3312 break;
3313 }
3314 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3315 QUIC_FALLTHROUGH_INTENDED;
3316 case IETF_EXTENSION_MESSAGE: {
3317 QuicMessageFrame message_frame;
3318 if (!ProcessMessageFrame(
3319 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3320 &message_frame)) {
3321 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3322 }
dschinazi118934b2019-06-13 18:09:08 -07003323 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3324 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003325 if (!visitor_->OnMessageFrame(message_frame)) {
3326 QUIC_DVLOG(1) << ENDPOINT
3327 << "Visitor asked to stop further processing.";
3328 // Returning true since there was no parsing error.
3329 return true;
3330 }
3331 break;
3332 }
3333 case IETF_CRYPTO: {
3334 QuicCryptoFrame frame;
3335 if (!ProcessCryptoFrame(reader, &frame)) {
3336 return RaiseError(QUIC_INVALID_FRAME_DATA);
3337 }
dschinazi118934b2019-06-13 18:09:08 -07003338 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003339 if (!visitor_->OnCryptoFrame(frame)) {
3340 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3341 // Returning true since there was no parsing error.
3342 return true;
3343 }
3344 break;
3345 }
3346
3347 default:
3348 set_detailed_error("Illegal frame type.");
3349 QUIC_DLOG(WARNING)
3350 << ENDPOINT
3351 << "Illegal frame type: " << static_cast<int>(frame_type);
3352 return RaiseError(QUIC_INVALID_FRAME_DATA);
3353 }
3354 }
3355 }
3356 return true;
3357}
3358
3359namespace {
3360// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3361inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3362 return (1u << num_bits) - 1;
3363}
3364
3365// Extract |num_bits| from |flags| offset by |offset|.
3366uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3367 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3368}
3369
3370// Extract the bit at position |offset| from |flags| as a bool.
3371bool ExtractBit(uint8_t flags, uint8_t offset) {
3372 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3373}
3374
3375// Set |num_bits|, offset by |offset| to |val| in |flags|.
3376void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3377 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3378 *flags |= val << offset;
3379}
3380
3381// Set the bit at position |offset| to |val| in |flags|.
3382void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3383 SetBits(flags, val ? 1 : 0, 1, offset);
3384}
3385} // namespace
3386
3387bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3388 uint8_t frame_type,
3389 QuicStreamFrame* frame) {
3390 uint8_t stream_flags = frame_type;
3391
3392 uint8_t stream_id_length = 0;
3393 uint8_t offset_length = 4;
3394 bool has_data_length = true;
3395 stream_flags &= ~kQuicFrameTypeStreamMask;
3396
3397 // Read from right to left: StreamID, Offset, Data Length, Fin.
3398 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3399 stream_flags >>= kQuicStreamIdShift;
3400
3401 offset_length = (stream_flags & kQuicStreamOffsetMask);
3402 // There is no encoding for 1 byte, only 0 and 2 through 8.
3403 if (offset_length > 0) {
3404 offset_length += 1;
3405 }
3406 stream_flags >>= kQuicStreamShift;
3407
3408 has_data_length =
3409 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3410 stream_flags >>= kQuicStreamDataLengthShift;
3411
3412 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3413
3414 uint64_t stream_id;
3415 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3416 set_detailed_error("Unable to read stream_id.");
3417 return false;
3418 }
3419 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3420
3421 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3422 set_detailed_error("Unable to read offset.");
3423 return false;
3424 }
3425
3426 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3427 QuicStringPiece data;
3428 if (has_data_length) {
3429 if (!reader->ReadStringPiece16(&data)) {
3430 set_detailed_error("Unable to read frame data.");
3431 return false;
3432 }
3433 } else {
3434 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3435 set_detailed_error("Unable to read frame data.");
3436 return false;
3437 }
3438 }
3439 frame->data_buffer = data.data();
3440 frame->data_length = static_cast<uint16_t>(data.length());
3441
3442 return true;
3443}
3444
3445bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3446 uint8_t frame_type,
3447 QuicStreamFrame* frame) {
3448 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003449 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003450 set_detailed_error("Unable to read stream_id.");
3451 return false;
3452 }
3453
3454 // If we have a data offset, read it. If not, set to 0.
3455 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3456 if (!reader->ReadVarInt62(&frame->offset)) {
3457 set_detailed_error("Unable to read stream data offset.");
3458 return false;
3459 }
3460 } else {
3461 // no offset in the frame, ensure it's 0 in the Frame.
3462 frame->offset = 0;
3463 }
3464
3465 // If we have a data length, read it. If not, set to 0.
3466 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3467 QuicIetfStreamDataLength length;
3468 if (!reader->ReadVarInt62(&length)) {
3469 set_detailed_error("Unable to read stream data length.");
3470 return false;
3471 }
3472 if (length > 0xffff) {
3473 set_detailed_error("Stream data length is too large.");
3474 return false;
3475 }
3476 frame->data_length = length;
3477 } else {
3478 // no length in the frame, it is the number of bytes remaining in the
3479 // packet.
3480 frame->data_length = reader->BytesRemaining();
3481 }
3482
3483 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3484 frame->fin = true;
3485 } else {
3486 frame->fin = false;
3487 }
3488
3489 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3490 QuicStringPiece data;
3491 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3492 set_detailed_error("Unable to read frame data.");
3493 return false;
3494 }
3495 frame->data_buffer = data.data();
3496 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3497
3498 return true;
3499}
3500
3501bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3502 QuicCryptoFrame* frame) {
3503 if (!reader->ReadVarInt62(&frame->offset)) {
3504 set_detailed_error("Unable to read crypto data offset.");
3505 return false;
3506 }
3507 uint64_t len;
3508 if (!reader->ReadVarInt62(&len) ||
3509 len > std::numeric_limits<QuicPacketLength>::max()) {
3510 set_detailed_error("Invalid data length.");
3511 return false;
3512 }
3513 frame->data_length = len;
3514
3515 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3516 QuicStringPiece data;
3517 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3518 set_detailed_error("Unable to read frame data.");
3519 return false;
3520 }
3521 frame->data_buffer = data.data();
3522 return true;
3523}
3524
3525bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3526 const bool has_ack_blocks =
3527 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3528 uint8_t num_ack_blocks = 0;
3529 uint8_t num_received_packets = 0;
3530
3531 // Determine the two lengths from the frame type: largest acked length,
3532 // ack block length.
3533 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
3534 version_.transport_version,
3535 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3536 kActBlockLengthOffset));
3537 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
3538 version_.transport_version,
3539 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3540 kLargestAckedOffset));
3541
3542 uint64_t largest_acked;
3543 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3544 set_detailed_error("Unable to read largest acked.");
3545 return false;
3546 }
3547
3548 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3549 // Connection always sends packet starting from kFirstSendingPacketNumber >
3550 // 0, peer has observed an unsent packet.
3551 set_detailed_error("Largest acked is 0.");
3552 return false;
3553 }
3554
3555 uint64_t ack_delay_time_us;
3556 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3557 set_detailed_error("Unable to read ack delay time.");
3558 return false;
3559 }
3560
3561 if (!visitor_->OnAckFrameStart(
3562 QuicPacketNumber(largest_acked),
3563 ack_delay_time_us == kUFloat16MaxValue
3564 ? QuicTime::Delta::Infinite()
3565 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3566 // The visitor suppresses further processing of the packet. Although this is
3567 // not a parsing error, returns false as this is in middle of processing an
3568 // ack frame,
3569 set_detailed_error("Visitor suppresses further processing of ack frame.");
3570 return false;
3571 }
3572
3573 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3574 set_detailed_error("Unable to read num of ack blocks.");
3575 return false;
3576 }
3577
3578 uint64_t first_block_length;
3579 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3580 set_detailed_error("Unable to read first ack block length.");
3581 return false;
3582 }
3583
3584 if (first_block_length == 0) {
3585 set_detailed_error("First block length is zero.");
3586 return false;
3587 }
3588 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3589 if (first_block_length + first_sending_packet_number_.ToUint64() >
3590 largest_acked + 1) {
3591 first_ack_block_underflow = true;
3592 }
3593 if (first_ack_block_underflow) {
3594 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3595 first_block_length, " largest acked is ",
3596 largest_acked, ".")
3597 .c_str());
3598 return false;
3599 }
3600
3601 uint64_t first_received = largest_acked + 1 - first_block_length;
3602 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3603 QuicPacketNumber(largest_acked + 1))) {
3604 // The visitor suppresses further processing of the packet. Although
3605 // this is not a parsing error, returns false as this is in middle
3606 // of processing an ack frame,
3607 set_detailed_error("Visitor suppresses further processing of ack frame.");
3608 return false;
3609 }
3610
3611 if (num_ack_blocks > 0) {
3612 for (size_t i = 0; i < num_ack_blocks; ++i) {
3613 uint8_t gap = 0;
3614 if (!reader->ReadUInt8(&gap)) {
3615 set_detailed_error("Unable to read gap to next ack block.");
3616 return false;
3617 }
3618 uint64_t current_block_length;
3619 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3620 set_detailed_error("Unable to ack block length.");
3621 return false;
3622 }
3623 bool ack_block_underflow = first_received < gap + current_block_length;
3624 if (first_received < gap + current_block_length +
3625 first_sending_packet_number_.ToUint64()) {
3626 ack_block_underflow = true;
3627 }
3628 if (ack_block_underflow) {
3629 set_detailed_error(
3630 QuicStrCat("Underflow with ack block length ", current_block_length,
3631 ", end of block is ", first_received - gap, ".")
3632 .c_str());
3633 return false;
3634 }
3635
3636 first_received -= (gap + current_block_length);
3637 if (current_block_length > 0) {
3638 if (!visitor_->OnAckRange(
3639 QuicPacketNumber(first_received),
3640 QuicPacketNumber(first_received) + current_block_length)) {
3641 // The visitor suppresses further processing of the packet. Although
3642 // this is not a parsing error, returns false as this is in middle
3643 // of processing an ack frame,
3644 set_detailed_error(
3645 "Visitor suppresses further processing of ack frame.");
3646 return false;
3647 }
3648 }
3649 }
3650 }
3651
3652 if (!reader->ReadUInt8(&num_received_packets)) {
3653 set_detailed_error("Unable to read num received packets.");
3654 return false;
3655 }
3656
3657 if (!ProcessTimestampsInAckFrame(num_received_packets,
3658 QuicPacketNumber(largest_acked), reader)) {
3659 return false;
3660 }
3661
3662 // Done processing the ACK frame.
3663 return visitor_->OnAckFrameEnd(QuicPacketNumber(first_received));
3664}
3665
3666bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3667 QuicPacketNumber largest_acked,
3668 QuicDataReader* reader) {
3669 if (num_received_packets == 0) {
3670 return true;
3671 }
3672 uint8_t delta_from_largest_observed;
3673 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3674 set_detailed_error("Unable to read sequence delta in received packets.");
3675 return false;
3676 }
3677
3678 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3679 set_detailed_error(QuicStrCat("delta_from_largest_observed too high: ",
3680 delta_from_largest_observed,
3681 ", largest_acked: ", largest_acked.ToUint64())
3682 .c_str());
3683 return false;
3684 }
3685
3686 // Time delta from the framer creation.
3687 uint32_t time_delta_us;
3688 if (!reader->ReadUInt32(&time_delta_us)) {
3689 set_detailed_error("Unable to read time delta in received packets.");
3690 return false;
3691 }
3692
3693 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3694 if (process_timestamps_) {
3695 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3696
3697 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3698 }
3699
3700 for (uint8_t i = 1; i < num_received_packets; ++i) {
3701 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3702 set_detailed_error("Unable to read sequence delta in received packets.");
3703 return false;
3704 }
3705 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3706 set_detailed_error(
3707 QuicStrCat("delta_from_largest_observed too high: ",
3708 delta_from_largest_observed,
3709 ", largest_acked: ", largest_acked.ToUint64())
3710 .c_str());
3711 return false;
3712 }
3713 seq_num = largest_acked - delta_from_largest_observed;
3714
3715 // Time delta from the previous timestamp.
3716 uint64_t incremental_time_delta_us;
3717 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3718 set_detailed_error(
3719 "Unable to read incremental time delta in received packets.");
3720 return false;
3721 }
3722
3723 if (process_timestamps_) {
3724 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3725 incremental_time_delta_us);
3726 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3727 }
3728 }
3729 return true;
3730}
3731
3732bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3733 uint64_t frame_type,
3734 QuicAckFrame* ack_frame) {
3735 uint64_t largest_acked;
3736 if (!reader->ReadVarInt62(&largest_acked)) {
3737 set_detailed_error("Unable to read largest acked.");
3738 return false;
3739 }
3740 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3741 // Connection always sends packet starting from kFirstSendingPacketNumber >
3742 // 0, peer has observed an unsent packet.
3743 set_detailed_error("Largest acked is 0.");
3744 return false;
3745 }
3746 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3747 uint64_t ack_delay_time_in_us;
3748 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3749 set_detailed_error("Unable to read ack delay time.");
3750 return false;
3751 }
3752
QUICHE teama6ef0a62019-03-07 20:34:33 -05003753 if (ack_delay_time_in_us == kVarInt62MaxValue) {
3754 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3755 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003756 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003757 ack_frame->ack_delay_time =
3758 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3759 }
3760 if (frame_type == IETF_ACK_ECN) {
3761 ack_frame->ecn_counters_populated = true;
3762 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3763 set_detailed_error("Unable to read ack ect_0_count.");
3764 return false;
3765 }
3766 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3767 set_detailed_error("Unable to read ack ect_1_count.");
3768 return false;
3769 }
3770 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3771 set_detailed_error("Unable to read ack ecn_ce_count.");
3772 return false;
3773 }
3774 } else {
3775 ack_frame->ecn_counters_populated = false;
3776 ack_frame->ect_0_count = 0;
3777 ack_frame->ect_1_count = 0;
3778 ack_frame->ecn_ce_count = 0;
3779 }
3780 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3781 ack_frame->ack_delay_time)) {
3782 // The visitor suppresses further processing of the packet. Although this is
3783 // not a parsing error, returns false as this is in middle of processing an
3784 // ACK frame.
3785 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3786 return false;
3787 }
3788
3789 // Get number of ACK blocks from the packet.
3790 uint64_t ack_block_count;
3791 if (!reader->ReadVarInt62(&ack_block_count)) {
3792 set_detailed_error("Unable to read ack block count.");
3793 return false;
3794 }
3795 // There always is a first ACK block, which is the (number of packets being
3796 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3797 // value is 0, then only largest is acked. If it is 1, then largest-1,
3798 // largest] are acked, etc
3799 uint64_t ack_block_value;
3800 if (!reader->ReadVarInt62(&ack_block_value)) {
3801 set_detailed_error("Unable to read first ack block length.");
3802 return false;
3803 }
3804 // Calculate the packets being acked in the first block.
3805 // +1 because AddRange implementation requires [low,high)
3806 uint64_t block_high = largest_acked + 1;
3807 uint64_t block_low = largest_acked - ack_block_value;
3808
3809 // ack_block_value is the number of packets preceding the
3810 // largest_acked packet which are in the block being acked. Thus,
3811 // its maximum value is largest_acked-1. Test this, reporting an
3812 // error if the value is wrong.
3813 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3814 largest_acked) {
3815 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3816 ack_block_value + 1, " largest acked is ",
3817 largest_acked, ".")
3818 .c_str());
3819 return false;
3820 }
3821
3822 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3823 QuicPacketNumber(block_high))) {
3824 // The visitor suppresses further processing of the packet. Although
3825 // this is not a parsing error, returns false as this is in middle
3826 // of processing an ACK frame.
3827 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3828 return false;
3829 }
3830
3831 while (ack_block_count != 0) {
3832 uint64_t gap_block_value;
3833 // Get the sizes of the gap and ack blocks,
3834 if (!reader->ReadVarInt62(&gap_block_value)) {
3835 set_detailed_error("Unable to read gap block value.");
3836 return false;
3837 }
3838 // It's an error if the gap is larger than the space from packet
3839 // number 0 to the start of the block that's just been acked, PLUS
3840 // there must be space for at least 1 packet to be acked. For
3841 // example, if block_low is 10 and gap_block_value is 9, it means
3842 // the gap block is 10 packets long, leaving no room for a packet
3843 // to be acked. Thus, gap_block_value+2 can not be larger than
3844 // block_low.
3845 // The test is written this way to detect wrap-arounds.
3846 if ((gap_block_value + 2) > block_low) {
3847 set_detailed_error(
3848 QuicStrCat("Underflow with gap block length ", gap_block_value + 1,
3849 " previous ack block start is ", block_low, ".")
3850 .c_str());
3851 return false;
3852 }
3853
3854 // Adjust block_high to be the top of the next ack block.
3855 // There is a gap of |gap_block_value| packets between the bottom
3856 // of ack block N and top of block N+1. Note that gap_block_value
3857 // is he size of the gap minus 1 (per the QUIC protocol), and
3858 // block_high is the packet number of the first packet of the gap
3859 // (per the implementation of OnAckRange/AddAckRange, below).
3860 block_high = block_low - 1 - gap_block_value;
3861
3862 if (!reader->ReadVarInt62(&ack_block_value)) {
3863 set_detailed_error("Unable to read ack block value.");
3864 return false;
3865 }
3866 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3867 (block_high - 1)) {
3868 set_detailed_error(
3869 QuicStrCat("Underflow with ack block length ", ack_block_value + 1,
3870 " latest ack block end is ", block_high - 1, ".")
3871 .c_str());
3872 return false;
3873 }
3874 // Calculate the low end of the new nth ack block. The +1 is
3875 // because the encoded value is the blocksize-1.
3876 block_low = block_high - 1 - ack_block_value;
3877 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3878 QuicPacketNumber(block_high))) {
3879 // The visitor suppresses further processing of the packet. Although
3880 // this is not a parsing error, returns false as this is in middle
3881 // of processing an ACK frame.
3882 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3883 return false;
3884 }
3885
3886 // Another one done.
3887 ack_block_count--;
3888 }
3889
3890 return visitor_->OnAckFrameEnd(QuicPacketNumber(block_low));
3891}
3892
3893bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3894 const QuicPacketHeader& header,
3895 QuicStopWaitingFrame* stop_waiting) {
3896 uint64_t least_unacked_delta;
3897 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3898 &least_unacked_delta)) {
3899 set_detailed_error("Unable to read least unacked delta.");
3900 return false;
3901 }
3902 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3903 set_detailed_error("Invalid unacked delta.");
3904 return false;
3905 }
3906 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3907
3908 return true;
3909}
3910
3911bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3912 QuicRstStreamFrame* frame) {
3913 if (!reader->ReadUInt32(&frame->stream_id)) {
3914 set_detailed_error("Unable to read stream_id.");
3915 return false;
3916 }
3917
3918 if (!reader->ReadUInt64(&frame->byte_offset)) {
3919 set_detailed_error("Unable to read rst stream sent byte offset.");
3920 return false;
3921 }
3922
3923 uint32_t error_code;
3924 if (!reader->ReadUInt32(&error_code)) {
3925 set_detailed_error("Unable to read rst stream error code.");
3926 return false;
3927 }
3928
3929 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3930 // Ignore invalid stream error code if any.
3931 error_code = QUIC_STREAM_LAST_ERROR;
3932 }
3933
3934 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3935
3936 return true;
3937}
3938
3939bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3940 QuicConnectionCloseFrame* frame) {
3941 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003942 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3943
QUICHE teama6ef0a62019-03-07 20:34:33 -05003944 if (!reader->ReadUInt32(&error_code)) {
3945 set_detailed_error("Unable to read connection close error code.");
3946 return false;
3947 }
3948
3949 if (error_code >= QUIC_LAST_ERROR) {
3950 // Ignore invalid QUIC error code if any.
3951 error_code = QUIC_LAST_ERROR;
3952 }
3953
fkastenholze9d71a82019-04-09 05:12:13 -07003954 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003955
3956 QuicStringPiece error_details;
3957 if (!reader->ReadStringPiece16(&error_details)) {
3958 set_detailed_error("Unable to read connection close error details.");
3959 return false;
3960 }
vasilvvc48c8712019-03-11 13:38:16 -07003961 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003962
3963 return true;
3964}
3965
3966bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3967 QuicGoAwayFrame* frame) {
3968 uint32_t error_code;
3969 if (!reader->ReadUInt32(&error_code)) {
3970 set_detailed_error("Unable to read go away error code.");
3971 return false;
3972 }
3973
3974 if (error_code >= QUIC_LAST_ERROR) {
3975 // Ignore invalid QUIC error code if any.
3976 error_code = QUIC_LAST_ERROR;
3977 }
3978 frame->error_code = static_cast<QuicErrorCode>(error_code);
3979
3980 uint32_t stream_id;
3981 if (!reader->ReadUInt32(&stream_id)) {
3982 set_detailed_error("Unable to read last good stream id.");
3983 return false;
3984 }
3985 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
3986
3987 QuicStringPiece reason_phrase;
3988 if (!reader->ReadStringPiece16(&reason_phrase)) {
3989 set_detailed_error("Unable to read goaway reason.");
3990 return false;
3991 }
vasilvvc48c8712019-03-11 13:38:16 -07003992 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003993
3994 return true;
3995}
3996
3997bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
3998 QuicWindowUpdateFrame* frame) {
3999 if (!reader->ReadUInt32(&frame->stream_id)) {
4000 set_detailed_error("Unable to read stream_id.");
4001 return false;
4002 }
4003
4004 if (!reader->ReadUInt64(&frame->byte_offset)) {
4005 set_detailed_error("Unable to read window byte_offset.");
4006 return false;
4007 }
4008
4009 return true;
4010}
4011
4012bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4013 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004014 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4015 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004016
4017 if (!reader->ReadUInt32(&frame->stream_id)) {
4018 set_detailed_error("Unable to read stream_id.");
4019 return false;
4020 }
4021
4022 return true;
4023}
4024
4025void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4026 QuicPaddingFrame* frame) {
4027 // Type byte has been read.
4028 frame->num_padding_bytes = 1;
4029 uint8_t next_byte;
4030 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4031 reader->ReadBytes(&next_byte, 1);
4032 DCHECK_EQ(0x00, next_byte);
4033 ++frame->num_padding_bytes;
4034 }
4035}
4036
4037bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4038 bool no_message_length,
4039 QuicMessageFrame* frame) {
4040 if (no_message_length) {
4041 QuicStringPiece remaining(reader->ReadRemainingPayload());
4042 frame->data = remaining.data();
4043 frame->message_length = remaining.length();
4044 return true;
4045 }
4046
4047 uint64_t message_length;
4048 if (!reader->ReadVarInt62(&message_length)) {
4049 set_detailed_error("Unable to read message length");
4050 return false;
4051 }
4052
4053 QuicStringPiece message_piece;
4054 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4055 set_detailed_error("Unable to read message data");
4056 return false;
4057 }
4058
4059 frame->data = message_piece.data();
4060 frame->message_length = message_length;
4061
4062 return true;
4063}
4064
4065// static
4066QuicStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
4067 QuicTransportVersion version,
4068 const QuicEncryptedPacket& encrypted,
4069 QuicConnectionIdLength destination_connection_id_length,
4070 QuicConnectionIdLength source_connection_id_length,
4071 bool includes_version,
4072 bool includes_diversification_nonce,
4073 QuicPacketNumberLength packet_number_length,
4074 QuicVariableLengthIntegerLength retry_token_length_length,
4075 uint64_t retry_token_length,
4076 QuicVariableLengthIntegerLength length_length) {
4077 // TODO(ianswett): This is identical to QuicData::AssociatedData.
4078 return QuicStringPiece(
4079 encrypted.data(),
4080 GetStartOfEncryptedData(version, destination_connection_id_length,
4081 source_connection_id_length, includes_version,
4082 includes_diversification_nonce,
4083 packet_number_length, retry_token_length_length,
4084 retry_token_length, length_length));
4085}
4086
4087void QuicFramer::SetDecrypter(EncryptionLevel level,
4088 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004089 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004090 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004091 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07004092 decrypter_[decrypter_level_] = nullptr;
4093 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004094 decrypter_level_ = level;
4095}
4096
4097void QuicFramer::SetAlternativeDecrypter(
4098 EncryptionLevel level,
4099 std::unique_ptr<QuicDecrypter> decrypter,
4100 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004101 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004102 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07004103 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4104 decrypter_[alternative_decrypter_level_] = nullptr;
4105 }
4106 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004107 alternative_decrypter_level_ = level;
4108 alternative_decrypter_latch_ = latch_once_used;
4109}
4110
zhongyi546cc452019-04-12 15:27:49 -07004111void QuicFramer::InstallDecrypter(EncryptionLevel level,
4112 std::unique_ptr<QuicDecrypter> decrypter) {
4113 DCHECK(version_.KnowsWhichDecrypterToUse());
4114 decrypter_[level] = std::move(decrypter);
4115}
4116
4117void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4118 DCHECK(version_.KnowsWhichDecrypterToUse());
4119 decrypter_[level] = nullptr;
4120}
4121
4122const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4123 DCHECK(version_.KnowsWhichDecrypterToUse());
4124 return decrypter_[level].get();
4125}
4126
QUICHE teama6ef0a62019-03-07 20:34:33 -05004127const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004128 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004129}
4130
4131const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004132 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4133 return nullptr;
4134 }
4135 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004136}
4137
4138void QuicFramer::SetEncrypter(EncryptionLevel level,
4139 std::unique_ptr<QuicEncrypter> encrypter) {
4140 DCHECK_GE(level, 0);
4141 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
4142 encrypter_[level] = std::move(encrypter);
4143}
4144
4145size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4146 QuicPacketNumber packet_number,
4147 size_t ad_len,
4148 size_t total_len,
4149 size_t buffer_len,
4150 char* buffer) {
4151 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004152 if (encrypter_[level] == nullptr) {
4153 QUIC_BUG << ENDPOINT
4154 << "Attempted to encrypt in place without encrypter at level "
4155 << QuicUtils::EncryptionLevelToString(level);
4156 RaiseError(QUIC_ENCRYPTION_FAILURE);
4157 return 0;
4158 }
4159
QUICHE teama6ef0a62019-03-07 20:34:33 -05004160 size_t output_length = 0;
4161 if (!encrypter_[level]->EncryptPacket(
4162 packet_number.ToUint64(),
4163 QuicStringPiece(buffer, ad_len), // Associated data
4164 QuicStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext
4165 buffer + ad_len, // Destination buffer
4166 &output_length, buffer_len - ad_len)) {
4167 RaiseError(QUIC_ENCRYPTION_FAILURE);
4168 return 0;
4169 }
nharper55fa6132019-05-07 19:37:21 -07004170 if (version_.HasHeaderProtection() &&
4171 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4172 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4173 RaiseError(QUIC_ENCRYPTION_FAILURE);
4174 return 0;
4175 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004176
4177 return ad_len + output_length;
4178}
4179
nharper55fa6132019-05-07 19:37:21 -07004180namespace {
4181
4182const size_t kHPSampleLen = 16;
4183
4184constexpr bool IsLongHeader(uint8_t type_byte) {
4185 return (type_byte & FLAGS_LONG_HEADER) != 0;
4186}
4187
4188} // namespace
4189
4190bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4191 char* buffer,
4192 size_t buffer_len,
4193 size_t ad_len) {
4194 QuicDataReader buffer_reader(buffer, buffer_len);
4195 QuicDataWriter buffer_writer(buffer_len, buffer);
4196 // The sample starts 4 bytes after the start of the packet number.
4197 if (ad_len < last_written_packet_number_length_) {
4198 return false;
4199 }
4200 size_t pn_offset = ad_len - last_written_packet_number_length_;
4201 // Sample the ciphertext and generate the mask to use for header protection.
4202 size_t sample_offset = pn_offset + 4;
4203 QuicDataReader sample_reader(buffer, buffer_len);
4204 QuicStringPiece sample;
4205 if (!sample_reader.Seek(sample_offset) ||
4206 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4207 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4208 << ", sample len: " << kHPSampleLen
4209 << ", buffer len: " << buffer_len;
4210 return false;
4211 }
4212
4213 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4214 if (mask.empty()) {
4215 QUIC_BUG << "Unable to generate header protection mask.";
4216 return false;
4217 }
4218 QuicDataReader mask_reader(mask.data(), mask.size());
4219
4220 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4221 uint8_t bitmask = 0x1f;
4222 uint8_t type_byte;
4223 if (!buffer_reader.ReadUInt8(&type_byte)) {
4224 return false;
4225 }
4226 QuicLongHeaderType header_type;
4227 if (IsLongHeader(type_byte)) {
4228 bitmask = 0x0f;
4229 if (!GetLongHeaderType(version_.transport_version, type_byte,
4230 &header_type)) {
4231 return false;
4232 }
4233 }
4234 uint8_t mask_byte;
4235 if (!mask_reader.ReadUInt8(&mask_byte) ||
4236 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4237 return false;
4238 }
4239
4240 // Adjust |pn_offset| to account for the diversification nonce.
4241 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4242 perspective_ == Perspective::IS_SERVER &&
4243 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4244 if (pn_offset <= kDiversificationNonceSize) {
4245 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4246 return false;
4247 }
4248 pn_offset -= kDiversificationNonceSize;
4249 }
4250 // Advance the reader and writer to the packet number. Both the reader and
4251 // writer have each read/written one byte.
4252 if (!buffer_writer.Seek(pn_offset - 1) ||
4253 !buffer_reader.Seek(pn_offset - 1)) {
4254 return false;
4255 }
4256 // Apply the rest of the mask to the packet number.
4257 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4258 uint8_t buffer_byte;
4259 uint8_t mask_byte;
4260 if (!mask_reader.ReadUInt8(&mask_byte) ||
4261 !buffer_reader.ReadUInt8(&buffer_byte) ||
4262 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4263 return false;
4264 }
4265 }
4266 return true;
4267}
4268
4269bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4270 const QuicEncryptedPacket& packet,
4271 QuicPacketHeader* header,
4272 uint64_t* full_packet_number,
4273 std::vector<char>* associated_data) {
4274 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4275 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4276 if (decrypter == nullptr) {
4277 QUIC_DVLOG(1)
4278 << "No decrypter available for removing header protection at level "
4279 << expected_decryption_level;
4280 return false;
4281 }
4282
4283 bool has_diversification_nonce =
4284 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4285 header->long_packet_type == ZERO_RTT_PROTECTED &&
4286 perspective_ == Perspective::IS_CLIENT &&
4287 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4288
4289 // Read a sample from the ciphertext and compute the mask to use for header
4290 // protection.
4291 QuicStringPiece remaining_packet = reader->PeekRemainingPayload();
4292 QuicDataReader sample_reader(remaining_packet);
4293
4294 // The sample starts 4 bytes after the start of the packet number.
4295 QuicStringPiece pn;
4296 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4297 QUIC_DVLOG(1) << "Not enough data to sample";
4298 return false;
4299 }
4300 if (has_diversification_nonce) {
4301 // In Google QUIC, the diversification nonce comes between the packet number
4302 // and the sample.
4303 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4304 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4305 return false;
4306 }
4307 }
4308 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4309 QuicDataReader mask_reader(mask.data(), mask.size());
4310 if (mask.empty()) {
4311 QUIC_DVLOG(1) << "Failed to compute mask";
4312 return false;
4313 }
4314
4315 // Unmask the rest of the type byte.
4316 uint8_t bitmask = 0x1f;
4317 if (IsLongHeader(header->type_byte)) {
4318 bitmask = 0x0f;
4319 }
4320 uint8_t mask_byte;
4321 if (!mask_reader.ReadUInt8(&mask_byte)) {
4322 QUIC_DVLOG(1) << "No first byte to read from mask";
4323 return false;
4324 }
4325 header->type_byte ^= (mask_byte & bitmask);
4326
4327 // Compute the packet number length.
4328 header->packet_number_length =
4329 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4330
4331 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
4332 QuicDataWriter pn_writer(QUIC_ARRAYSIZE(pn_buffer), pn_buffer);
4333
4334 // Read the (protected) packet number from the reader and unmask the packet
4335 // number.
4336 for (size_t i = 0; i < header->packet_number_length; ++i) {
4337 uint8_t protected_pn_byte, mask_byte;
4338 if (!mask_reader.ReadUInt8(&mask_byte) ||
4339 !reader->ReadUInt8(&protected_pn_byte) ||
4340 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4341 QUIC_DVLOG(1) << "Failed to unmask packet number";
4342 return false;
4343 }
4344 }
4345 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4346 QuicPacketNumber base_packet_number;
4347 if (supports_multiple_packet_number_spaces_) {
4348 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4349 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4350 return false;
4351 }
4352 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4353 } else {
4354 base_packet_number = largest_packet_number_;
4355 }
4356 if (!ProcessAndCalculatePacketNumber(
4357 &packet_number_reader, header->packet_number_length,
4358 base_packet_number, full_packet_number)) {
4359 return false;
4360 }
4361
4362 // Get the associated data, and apply the same unmasking operations to it.
4363 QuicStringPiece ad = GetAssociatedDataFromEncryptedPacket(
4364 version_.transport_version, packet,
4365 GetIncludedDestinationConnectionIdLength(*header),
4366 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4367 has_diversification_nonce, header->packet_number_length,
4368 header->retry_token_length_length, header->retry_token.length(),
4369 header->length_length);
4370 *associated_data = std::vector<char>(ad.begin(), ad.end());
4371 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4372
4373 // Apply the unmasked type byte and packet number to |associated_data|.
4374 if (!ad_writer.WriteUInt8(header->type_byte)) {
4375 return false;
4376 }
4377 // Put the packet number at the end of the AD, or if there's a diversification
4378 // nonce, before that (which is at the end of the AD).
4379 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4380 if (has_diversification_nonce) {
4381 seek_len -= kDiversificationNonceSize;
4382 }
4383 if (!ad_writer.Seek(seek_len) ||
4384 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4385 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4386 return false;
4387 }
4388
4389 return true;
4390}
4391
QUICHE teama6ef0a62019-03-07 20:34:33 -05004392size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4393 QuicPacketNumber packet_number,
4394 const QuicPacket& packet,
4395 char* buffer,
4396 size_t buffer_len) {
4397 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004398 if (encrypter_[level] == nullptr) {
4399 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
4400 << QuicUtils::EncryptionLevelToString(level);
4401 RaiseError(QUIC_ENCRYPTION_FAILURE);
4402 return 0;
4403 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004404
4405 QuicStringPiece associated_data =
4406 packet.AssociatedData(version_.transport_version);
4407 // Copy in the header, because the encrypter only populates the encrypted
4408 // plaintext content.
4409 const size_t ad_len = associated_data.length();
4410 memmove(buffer, associated_data.data(), ad_len);
4411 // Encrypt the plaintext into the buffer.
4412 size_t output_length = 0;
4413 if (!encrypter_[level]->EncryptPacket(
4414 packet_number.ToUint64(), associated_data,
4415 packet.Plaintext(version_.transport_version), buffer + ad_len,
4416 &output_length, buffer_len - ad_len)) {
4417 RaiseError(QUIC_ENCRYPTION_FAILURE);
4418 return 0;
4419 }
nharper55fa6132019-05-07 19:37:21 -07004420 if (version_.HasHeaderProtection() &&
4421 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4422 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4423 RaiseError(QUIC_ENCRYPTION_FAILURE);
4424 return 0;
4425 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004426
4427 return ad_len + output_length;
4428}
4429
4430size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4431 size_t plaintext_size) const {
4432 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4433}
4434
4435size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4436 // In order to keep the code simple, we don't have the current encryption
4437 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4438 size_t min_plaintext_size = ciphertext_size;
4439
QUICHE team6987b4a2019-03-15 16:23:04 -07004440 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004441 if (encrypter_[i] != nullptr) {
4442 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4443 if (size < min_plaintext_size) {
4444 min_plaintext_size = size;
4445 }
4446 }
4447 }
4448
4449 return min_plaintext_size;
4450}
4451
4452bool QuicFramer::DecryptPayload(QuicStringPiece encrypted,
4453 QuicStringPiece associated_data,
4454 const QuicPacketHeader& header,
4455 char* decrypted_buffer,
4456 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004457 size_t* decrypted_length,
4458 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004459 if (!EncryptionLevelIsValid(decrypter_level_)) {
4460 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4461 return false;
4462 }
zhongyi546cc452019-04-12 15:27:49 -07004463 EncryptionLevel level = decrypter_level_;
4464 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004465 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004466 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004467 if (header.form == GOOGLE_QUIC_PACKET) {
4468 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4469 "knows which decrypter to use";
4470 return false;
4471 }
zhongyi546cc452019-04-12 15:27:49 -07004472 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004473 if (!EncryptionLevelIsValid(level)) {
4474 QUIC_BUG << "Attempted to decrypt with bad level";
4475 return false;
4476 }
zhongyi546cc452019-04-12 15:27:49 -07004477 decrypter = decrypter_[level].get();
4478 if (decrypter == nullptr) {
4479 return false;
4480 }
4481 if (level == ENCRYPTION_ZERO_RTT &&
4482 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4483 decrypter->SetDiversificationNonce(*header.nonce);
4484 }
4485 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004486 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4487 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4488 return false;
4489 }
QUICHE team76086e42019-03-25 15:12:29 -07004490 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4491 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004492
nharper855d2172019-05-02 16:17:46 -07004493 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004494 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4495 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004496 return false;
4497 }
zhongyi546cc452019-04-12 15:27:49 -07004498
4499 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004500 header.packet_number.ToUint64(), associated_data, encrypted,
4501 decrypted_buffer, decrypted_length, buffer_length);
4502 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004503 visitor_->OnDecryptedPacket(level);
4504 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004505 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004506 if (header.nonce != nullptr) {
4507 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004508 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004509 }
4510 bool try_alternative_decryption = true;
4511 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4512 if (perspective_ == Perspective::IS_CLIENT) {
4513 if (header.nonce == nullptr) {
4514 // Can not use INITIAL decryption without a diversification nonce.
4515 try_alternative_decryption = false;
4516 }
4517 } else {
4518 DCHECK(header.nonce == nullptr);
4519 }
4520 }
4521
4522 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004523 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004524 header.packet_number.ToUint64(), associated_data, encrypted,
4525 decrypted_buffer, decrypted_length, buffer_length);
4526 }
4527 if (success) {
4528 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004529 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004530 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004531 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4532 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4533 "alternative_decrypter_level_";
4534 return false;
4535 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004536 // Switch to the alternative decrypter and latch so that we cannot
4537 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004538 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004539 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004540 } else {
4541 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004542 EncryptionLevel level = alternative_decrypter_level_;
4543 alternative_decrypter_level_ = decrypter_level_;
4544 decrypter_level_ = level;
4545 }
4546 }
4547 }
4548
4549 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004550 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004551 return false;
4552 }
4553
4554 return true;
4555}
4556
4557size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4558 // Type byte, largest_acked, and delay_time are straight-forward.
4559 size_t ack_frame_size = kQuicFrameTypeSize;
4560 QuicPacketNumber largest_acked = LargestAcked(frame);
4561 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4562 uint64_t ack_delay_time_us;
4563 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004564 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004565 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4566
4567 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4568 // then the ecn counters are included...
4569 if (frame.ecn_counters_populated &&
4570 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4571 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4572 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4573 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4574 }
4575
4576 // The rest (ack_block_count, first_ack_block, and additional ack
4577 // blocks, if any) depends:
4578 uint64_t ack_block_count = frame.packets.NumIntervals();
4579 if (ack_block_count == 0) {
4580 // If the QuicAckFrame has no Intervals, then it is interpreted
4581 // as an ack of a single packet at QuicAckFrame.largest_acked.
4582 // The resulting ack will consist of only the frame's
4583 // largest_ack & first_ack_block fields. The first ack block will be 0
4584 // (indicating a single packet) and the ack block_count will be 0.
4585 // Each 0 takes 1 byte when VarInt62 encoded.
4586 ack_frame_size += 2;
4587 return ack_frame_size;
4588 }
4589
4590 auto itr = frame.packets.rbegin();
4591 QuicPacketNumber ack_block_largest = largest_acked;
4592 QuicPacketNumber ack_block_smallest;
4593 if ((itr->max() - 1) == largest_acked) {
4594 // If largest_acked + 1 is equal to the Max() of the first Interval
4595 // in the QuicAckFrame then the first Interval is the first ack block of the
4596 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4597 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4598 // the remaining Intervals are encoded in additional ack blocks in the
4599 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4600 // Intervals - 1.
4601 ack_block_smallest = itr->min();
4602 itr++;
4603 ack_block_count--;
4604 } else {
4605 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4606 // the first Interval then it is interpreted as acking a single
4607 // packet at QuicAckFrame.largest_acked, with additional
4608 // Intervals indicating additional ack blocks. The encoding is
4609 // a) The packet's largest_acked is the QuicAckFrame's largest
4610 // acked,
4611 // b) the first ack block size is 0,
4612 // c) The packet's ack_block_count is the number of QuicAckFrame
4613 // Intervals, and
4614 // d) The QuicAckFrame Intervals are encoded in additional ack
4615 // blocks in the packet.
4616 ack_block_smallest = largest_acked;
4617 }
4618 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4619 ack_frame_size += ack_block_count_size;
4620
4621 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4622 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4623 ack_frame_size += first_ack_block_size;
4624
4625 // Account for the remaining Intervals, if any.
4626 while (ack_block_count != 0) {
4627 uint64_t gap_size = ack_block_smallest - itr->max();
4628 // Decrement per the protocol specification
4629 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4630 ack_frame_size += size_of_gap_size;
4631
4632 uint64_t block_size = itr->max() - itr->min();
4633 // Decrement per the protocol specification
4634 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4635 ack_frame_size += size_of_block_size;
4636
4637 ack_block_smallest = itr->min();
4638 itr++;
4639 ack_block_count--;
4640 }
4641
4642 return ack_frame_size;
4643}
4644
4645size_t QuicFramer::GetAckFrameSize(
4646 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004647 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004648 DCHECK(!ack.packets.Empty());
4649 size_t ack_size = 0;
4650
fkastenholz305e1732019-06-18 05:01:22 -07004651 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004652 return GetIetfAckFrameSize(ack);
4653 }
4654 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4655 QuicPacketNumberLength largest_acked_length =
4656 GetMinPacketNumberLength(version_.transport_version, LargestAcked(ack));
4657 QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(
4658 version_.transport_version, QuicPacketNumber(ack_info.max_block_length));
4659
4660 ack_size =
4661 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4662 // First ack block length.
4663 ack_size += ack_block_length;
4664 if (ack_info.num_ack_blocks != 0) {
4665 ack_size += kNumberOfAckBlocksSize;
4666 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4667 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4668 }
4669
4670 // Include timestamps.
4671 if (process_timestamps_) {
4672 ack_size += GetAckFrameTimeStampSize(ack);
4673 }
4674
4675 return ack_size;
4676}
4677
4678size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4679 if (ack.received_packet_times.empty()) {
4680 return 0;
4681 }
4682
4683 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4684 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4685 (ack.received_packet_times.size() - 1);
4686}
4687
4688size_t QuicFramer::ComputeFrameLength(
4689 const QuicFrame& frame,
4690 bool last_frame_in_packet,
4691 QuicPacketNumberLength packet_number_length) {
4692 switch (frame.type) {
4693 case STREAM_FRAME:
4694 return GetMinStreamFrameSize(
4695 version_.transport_version, frame.stream_frame.stream_id,
4696 frame.stream_frame.offset, last_frame_in_packet,
4697 frame.stream_frame.data_length) +
4698 frame.stream_frame.data_length;
4699 case CRYPTO_FRAME:
4700 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4701 frame.crypto_frame->data_length) +
4702 frame.crypto_frame->data_length;
4703 case ACK_FRAME: {
4704 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4705 }
4706 case STOP_WAITING_FRAME:
4707 return GetStopWaitingFrameSize(version_.transport_version,
4708 packet_number_length);
4709 case MTU_DISCOVERY_FRAME:
4710 // MTU discovery frames are serialized as ping frames.
4711 return kQuicFrameTypeSize;
4712 case MESSAGE_FRAME:
4713 return GetMessageFrameSize(version_.transport_version,
4714 last_frame_in_packet,
4715 frame.message_frame->message_length);
4716 case PADDING_FRAME:
4717 DCHECK(false);
4718 return 0;
4719 default:
4720 return GetRetransmittableControlFrameSize(version_.transport_version,
4721 frame);
4722 }
4723}
4724
4725bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4726 bool last_frame_in_packet,
4727 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004728 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004729 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4730 }
4731 uint8_t type_byte = 0;
4732 switch (frame.type) {
4733 case STREAM_FRAME:
4734 type_byte =
4735 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4736 break;
4737 case ACK_FRAME:
4738 return true;
4739 case MTU_DISCOVERY_FRAME:
4740 type_byte = static_cast<uint8_t>(PING_FRAME);
4741 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004742 case NEW_CONNECTION_ID_FRAME:
4743 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004744 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004745 return RaiseError(QUIC_INTERNAL_ERROR);
4746 case RETIRE_CONNECTION_ID_FRAME:
4747 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004748 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004749 return RaiseError(QUIC_INTERNAL_ERROR);
4750 case NEW_TOKEN_FRAME:
4751 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004752 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004753 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004754 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004755 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004756 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004757 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004758 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004759 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004760 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004761 return RaiseError(QUIC_INTERNAL_ERROR);
4762 case PATH_RESPONSE_FRAME:
4763 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004764 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004765 return RaiseError(QUIC_INTERNAL_ERROR);
4766 case PATH_CHALLENGE_FRAME:
4767 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004768 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004769 return RaiseError(QUIC_INTERNAL_ERROR);
4770 case STOP_SENDING_FRAME:
4771 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004772 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004773 return RaiseError(QUIC_INTERNAL_ERROR);
4774 case MESSAGE_FRAME:
4775 return true;
4776
4777 default:
4778 type_byte = static_cast<uint8_t>(frame.type);
4779 break;
4780 }
4781
4782 return writer->WriteUInt8(type_byte);
4783}
4784
4785bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4786 bool last_frame_in_packet,
4787 QuicDataWriter* writer) {
4788 uint8_t type_byte = 0;
4789 switch (frame.type) {
4790 case PADDING_FRAME:
4791 type_byte = IETF_PADDING;
4792 break;
4793 case RST_STREAM_FRAME:
4794 type_byte = IETF_RST_STREAM;
4795 break;
4796 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004797 switch (frame.connection_close_frame->close_type) {
4798 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4799 type_byte = IETF_APPLICATION_CLOSE;
4800 break;
4801 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4802 type_byte = IETF_CONNECTION_CLOSE;
4803 break;
4804 default:
4805 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4806 return RaiseError(QUIC_INTERNAL_ERROR);
4807 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004808 break;
4809 case GOAWAY_FRAME:
4810 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004811 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004812 return RaiseError(QUIC_INTERNAL_ERROR);
4813 case WINDOW_UPDATE_FRAME:
4814 // Depending on whether there is a stream ID or not, will be either a
4815 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4816 if (frame.window_update_frame->stream_id ==
4817 QuicUtils::GetInvalidStreamId(transport_version())) {
4818 type_byte = IETF_MAX_DATA;
4819 } else {
4820 type_byte = IETF_MAX_STREAM_DATA;
4821 }
4822 break;
4823 case BLOCKED_FRAME:
4824 if (frame.blocked_frame->stream_id ==
4825 QuicUtils::GetInvalidStreamId(transport_version())) {
4826 type_byte = IETF_BLOCKED;
4827 } else {
4828 type_byte = IETF_STREAM_BLOCKED;
4829 }
4830 break;
4831 case STOP_WAITING_FRAME:
4832 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004833 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004834 return RaiseError(QUIC_INTERNAL_ERROR);
4835 case PING_FRAME:
4836 type_byte = IETF_PING;
4837 break;
4838 case STREAM_FRAME:
4839 type_byte =
4840 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4841 break;
4842 case ACK_FRAME:
4843 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4844 // in the buffer.
4845 return true;
4846 case MTU_DISCOVERY_FRAME:
4847 // The path MTU discovery frame is encoded as a PING frame on the wire.
4848 type_byte = IETF_PING;
4849 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004850 case NEW_CONNECTION_ID_FRAME:
4851 type_byte = IETF_NEW_CONNECTION_ID;
4852 break;
4853 case RETIRE_CONNECTION_ID_FRAME:
4854 type_byte = IETF_RETIRE_CONNECTION_ID;
4855 break;
4856 case NEW_TOKEN_FRAME:
4857 type_byte = IETF_NEW_TOKEN;
4858 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004859 case MAX_STREAMS_FRAME:
4860 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004861 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004862 } else {
4863 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004864 }
4865 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004866 case STREAMS_BLOCKED_FRAME:
4867 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004868 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004869 } else {
4870 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004871 }
4872 break;
4873 case PATH_RESPONSE_FRAME:
4874 type_byte = IETF_PATH_RESPONSE;
4875 break;
4876 case PATH_CHALLENGE_FRAME:
4877 type_byte = IETF_PATH_CHALLENGE;
4878 break;
4879 case STOP_SENDING_FRAME:
4880 type_byte = IETF_STOP_SENDING;
4881 break;
4882 case MESSAGE_FRAME:
4883 return true;
4884 case CRYPTO_FRAME:
4885 type_byte = IETF_CRYPTO;
4886 break;
4887 default:
4888 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4889 << frame.type;
4890 return false;
4891 }
4892 return writer->WriteUInt8(type_byte);
4893}
4894
4895// static
4896bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4897 QuicPacketNumber packet_number,
4898 QuicDataWriter* writer) {
4899 DCHECK(packet_number.IsInitialized());
4900 if (!IsValidPacketNumberLength(packet_number_length)) {
4901 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4902 return false;
4903 }
4904 return writer->WriteBytesToUInt64(packet_number_length,
4905 packet_number.ToUint64());
4906}
4907
4908// static
4909bool QuicFramer::AppendStreamId(size_t stream_id_length,
4910 QuicStreamId stream_id,
4911 QuicDataWriter* writer) {
4912 if (stream_id_length == 0 || stream_id_length > 4) {
4913 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4914 return false;
4915 }
4916 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4917}
4918
4919// static
4920bool QuicFramer::AppendStreamOffset(size_t offset_length,
4921 QuicStreamOffset offset,
4922 QuicDataWriter* writer) {
4923 if (offset_length == 1 || offset_length > 8) {
4924 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4925 return false;
4926 }
4927
4928 return writer->WriteBytesToUInt64(offset_length, offset);
4929}
4930
4931// static
4932bool QuicFramer::AppendAckBlock(uint8_t gap,
4933 QuicPacketNumberLength length_length,
4934 uint64_t length,
4935 QuicDataWriter* writer) {
4936 if (length == 0) {
4937 if (!IsValidPacketNumberLength(length_length)) {
4938 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4939 return false;
4940 }
4941 return writer->WriteUInt8(gap) &&
4942 writer->WriteBytesToUInt64(length_length, length);
4943 }
4944 return writer->WriteUInt8(gap) &&
4945 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4946}
4947
4948bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4949 bool no_stream_frame_length,
4950 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004951 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004952 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4953 }
4954 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4955 writer)) {
4956 QUIC_BUG << "Writing stream id size failed.";
4957 return false;
4958 }
4959 if (!AppendStreamOffset(
4960 GetStreamOffsetSize(version_.transport_version, frame.offset),
4961 frame.offset, writer)) {
4962 QUIC_BUG << "Writing offset size failed.";
4963 return false;
4964 }
4965 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07004966 static_assert(
wubeff50282019-06-19 09:04:30 -07004967 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07004968 std::numeric_limits<uint16_t>::max(),
4969 "If frame.data_length can hold more than a uint16_t than we need to "
4970 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
4971 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004972 QUIC_BUG << "Writing stream frame length failed";
4973 return false;
4974 }
4975 }
4976
4977 if (data_producer_ != nullptr) {
4978 DCHECK_EQ(nullptr, frame.data_buffer);
4979 if (frame.data_length == 0) {
4980 return true;
4981 }
4982 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
4983 frame.data_length,
4984 writer) != WRITE_SUCCESS) {
4985 QUIC_BUG << "Writing frame data failed.";
4986 return false;
4987 }
4988 return true;
4989 }
4990
4991 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
4992 QUIC_BUG << "Writing frame data failed.";
4993 return false;
4994 }
4995 return true;
4996}
4997
QUICHE teama6ef0a62019-03-07 20:34:33 -05004998bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
4999 QuicDataWriter* writer) {
5000 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5001 set_detailed_error("Writing token length failed.");
5002 return false;
5003 }
5004 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5005 set_detailed_error("Writing token buffer failed.");
5006 return false;
5007 }
5008 return true;
5009}
5010
5011bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5012 QuicNewTokenFrame* frame) {
5013 uint64_t length;
5014 if (!reader->ReadVarInt62(&length)) {
5015 set_detailed_error("Unable to read new token length.");
5016 return false;
5017 }
5018 if (length > kMaxNewTokenTokenLength) {
5019 set_detailed_error("Token length larger than maximum.");
5020 return false;
5021 }
5022
5023 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
5024 QuicStringPiece data;
5025 if (!reader->ReadStringPiece(&data, length)) {
5026 set_detailed_error("Unable to read new token data.");
5027 return false;
5028 }
vasilvvc48c8712019-03-11 13:38:16 -07005029 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005030 return true;
5031}
5032
5033// Add a new ietf-format stream frame.
5034// Bits controlling whether there is a frame-length and frame-offset
5035// are in the QuicStreamFrame.
5036bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5037 bool last_frame_in_packet,
5038 QuicDataWriter* writer) {
5039 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5040 set_detailed_error("Writing stream id failed.");
5041 return false;
5042 }
5043
5044 if (frame.offset != 0) {
5045 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5046 set_detailed_error("Writing data offset failed.");
5047 return false;
5048 }
5049 }
5050
5051 if (!last_frame_in_packet) {
5052 if (!writer->WriteVarInt62(frame.data_length)) {
5053 set_detailed_error("Writing data length failed.");
5054 return false;
5055 }
5056 }
5057
5058 if (frame.data_length == 0) {
5059 return true;
5060 }
5061 if (data_producer_ == nullptr) {
5062 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5063 set_detailed_error("Writing frame data failed.");
5064 return false;
5065 }
5066 } else {
5067 DCHECK_EQ(nullptr, frame.data_buffer);
5068
5069 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5070 frame.data_length,
5071 writer) != WRITE_SUCCESS) {
5072 set_detailed_error("Writing frame data failed.");
5073 return false;
5074 }
5075 }
5076 return true;
5077}
5078
5079bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5080 QuicDataWriter* writer) {
5081 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5082 set_detailed_error("Writing data offset failed.");
5083 return false;
5084 }
5085 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5086 set_detailed_error("Writing data length failed.");
5087 return false;
5088 }
5089 if (data_producer_ == nullptr) {
5090 if (frame.data_buffer == nullptr ||
5091 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5092 set_detailed_error("Writing frame data failed.");
5093 return false;
5094 }
5095 } else {
5096 DCHECK_EQ(nullptr, frame.data_buffer);
5097 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5098 frame.data_length, writer)) {
5099 return false;
5100 }
5101 }
5102 return true;
5103}
5104
5105void QuicFramer::set_version(const ParsedQuicVersion version) {
5106 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5107 version_ = version;
5108}
5109
5110bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5111 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005112 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005113 return AppendIetfAckFrameAndTypeByte(frame, writer);
5114 }
5115
5116 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5117 QuicPacketNumber largest_acked = LargestAcked(frame);
5118 QuicPacketNumberLength largest_acked_length =
5119 GetMinPacketNumberLength(version_.transport_version, largest_acked);
5120 QuicPacketNumberLength ack_block_length =
5121 GetMinPacketNumberLength(version_.transport_version,
5122 QuicPacketNumber(new_ack_info.max_block_length));
5123 // Calculate available bytes for timestamps and ack blocks.
5124 int32_t available_timestamp_and_ack_block_bytes =
5125 writer->capacity() - writer->length() - ack_block_length -
5126 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5127 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5128 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5129
5130 // Write out the type byte by setting the low order bits and doing shifts
5131 // to make room for the next bit flags to be set.
5132 // Whether there are multiple ack blocks.
5133 uint8_t type_byte = 0;
5134 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5135 kQuicHasMultipleAckBlocksOffset);
5136
5137 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5138 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5139
5140 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5141 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5142
5143 type_byte |= kQuicFrameTypeAckMask;
5144
5145 if (!writer->WriteUInt8(type_byte)) {
5146 return false;
5147 }
5148
5149 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5150 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5151
5152 // Number of ack blocks.
5153 size_t num_ack_blocks =
5154 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5155 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5156 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5157 }
5158
5159 // Largest acked.
5160 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5161 return false;
5162 }
5163
5164 // Largest acked delta time.
5165 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5166 if (!frame.ack_delay_time.IsInfinite()) {
5167 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5168 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5169 }
5170 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5171 return false;
5172 }
5173
5174 if (num_ack_blocks > 0) {
5175 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5176 return false;
5177 }
5178 }
5179
5180 // First ack block length.
5181 if (!AppendPacketNumber(ack_block_length,
5182 QuicPacketNumber(new_ack_info.first_block_length),
5183 writer)) {
5184 return false;
5185 }
5186
5187 // Ack blocks.
5188 if (num_ack_blocks > 0) {
5189 size_t num_ack_blocks_written = 0;
5190 // Append, in descending order from the largest ACKed packet, a series of
5191 // ACK blocks that represents the successfully acknoweldged packets. Each
5192 // appended gap/block length represents a descending delta from the previous
5193 // block. i.e.:
5194 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5195 // For gaps larger than can be represented by a single encoded gap, a 0
5196 // length gap of the maximum is used, i.e.:
5197 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5198 auto itr = frame.packets.rbegin();
5199 QuicPacketNumber previous_start = itr->min();
5200 ++itr;
5201
5202 for (;
5203 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5204 previous_start = itr->min(), ++itr) {
5205 const auto& interval = *itr;
5206 const uint64_t total_gap = previous_start - interval.max();
5207 const size_t num_encoded_gaps =
5208 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5209 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005210
5211 // Append empty ACK blocks because the gap is longer than a single gap.
5212 for (size_t i = 1;
5213 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5214 ++i) {
5215 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5216 ack_block_length, 0, writer)) {
5217 return false;
5218 }
5219 ++num_ack_blocks_written;
5220 }
5221 if (num_ack_blocks_written >= num_ack_blocks) {
5222 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5223 QUIC_BUG << "Wrote " << num_ack_blocks_written
5224 << ", expected to write " << num_ack_blocks;
5225 }
5226 break;
5227 }
5228
5229 const uint8_t last_gap =
5230 total_gap -
5231 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5232 // Append the final ACK block with a non-empty size.
5233 if (!AppendAckBlock(last_gap, ack_block_length,
5234 PacketNumberIntervalLength(interval), writer)) {
5235 return false;
5236 }
5237 ++num_ack_blocks_written;
5238 }
5239 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5240 }
5241 // Timestamps.
5242 // If we don't process timestamps or if we don't have enough available space
5243 // to append all the timestamps, don't append any of them.
5244 if (process_timestamps_ && writer->capacity() - writer->length() >=
5245 GetAckFrameTimeStampSize(frame)) {
5246 if (!AppendTimestampsToAckFrame(frame, writer)) {
5247 return false;
5248 }
5249 } else {
5250 uint8_t num_received_packets = 0;
5251 if (!writer->WriteBytes(&num_received_packets, 1)) {
5252 return false;
5253 }
5254 }
5255
5256 return true;
5257}
5258
5259bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5260 QuicDataWriter* writer) {
5261 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5262 frame.received_packet_times.size());
5263 // num_received_packets is only 1 byte.
5264 if (frame.received_packet_times.size() >
5265 std::numeric_limits<uint8_t>::max()) {
5266 return false;
5267 }
5268
5269 uint8_t num_received_packets = frame.received_packet_times.size();
5270 if (!writer->WriteBytes(&num_received_packets, 1)) {
5271 return false;
5272 }
5273 if (num_received_packets == 0) {
5274 return true;
5275 }
5276
5277 auto it = frame.received_packet_times.begin();
5278 QuicPacketNumber packet_number = it->first;
5279 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5280
5281 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5282 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5283 return false;
5284 }
5285
5286 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5287 return false;
5288 }
5289
5290 // Use the lowest 4 bytes of the time delta from the creation_time_.
5291 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5292 uint32_t time_delta_us =
5293 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5294 (time_epoch_delta_us - 1));
5295 if (!writer->WriteUInt32(time_delta_us)) {
5296 return false;
5297 }
5298
5299 QuicTime prev_time = it->second;
5300
5301 for (++it; it != frame.received_packet_times.end(); ++it) {
5302 packet_number = it->first;
5303 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5304
5305 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5306 return false;
5307 }
5308
5309 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5310 return false;
5311 }
5312
5313 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5314 prev_time = it->second;
5315 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5316 return false;
5317 }
5318 }
5319 return true;
5320}
5321
5322bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5323 const QuicStopWaitingFrame& frame,
5324 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005325 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005326 DCHECK(frame.least_unacked.IsInitialized() &&
5327 header.packet_number >= frame.least_unacked);
5328 const uint64_t least_unacked_delta =
5329 header.packet_number - frame.least_unacked;
5330 const uint64_t length_shift = header.packet_number_length * 8;
5331
5332 if (least_unacked_delta >> length_shift > 0) {
5333 QUIC_BUG << "packet_number_length " << header.packet_number_length
5334 << " is too small for least_unacked_delta: " << least_unacked_delta
5335 << " packet_number:" << header.packet_number
5336 << " least_unacked:" << frame.least_unacked
5337 << " version:" << version_.transport_version;
5338 return false;
5339 }
5340 if (least_unacked_delta == 0) {
5341 return writer->WriteBytesToUInt64(header.packet_number_length,
5342 least_unacked_delta);
5343 }
5344 if (!AppendPacketNumber(header.packet_number_length,
5345 QuicPacketNumber(least_unacked_delta), writer)) {
5346 QUIC_BUG << " seq failed: " << header.packet_number_length;
5347 return false;
5348 }
5349
5350 return true;
5351}
5352
5353int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005354 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005355 size_t available_space) {
5356 // Number of blocks requested in the frame
5357 uint64_t ack_block_count = frame.packets.NumIntervals();
5358
5359 auto itr = frame.packets.rbegin();
5360
5361 int actual_block_count = 1;
5362 uint64_t block_length = itr->max() - itr->min();
5363 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5364 if (encoded_size > available_space) {
5365 return 0;
5366 }
5367 available_space -= encoded_size;
5368 QuicPacketNumber previous_ack_end = itr->min();
5369 ack_block_count--;
5370
5371 while (ack_block_count) {
5372 // Each block is a gap followed by another ACK. Calculate each value,
5373 // determine the encoded lengths, and check against the available space.
5374 itr++;
5375 size_t gap = previous_ack_end - itr->max() - 1;
5376 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5377
5378 // Add the ACK block.
5379 block_length = itr->max() - itr->min();
5380 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5381
5382 if (encoded_size > available_space) {
5383 // No room for this block, so what we've
5384 // done up to now is all that can be done.
5385 return actual_block_count;
5386 }
5387 available_space -= encoded_size;
5388 actual_block_count++;
5389 previous_ack_end = itr->min();
5390 ack_block_count--;
5391 }
5392 // Ran through the whole thing! We can do all blocks.
5393 return actual_block_count;
5394}
5395
5396bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5397 QuicDataWriter* writer) {
5398 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5399 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5400 uint8_t type = IETF_ACK;
5401 if (frame.ecn_counters_populated &&
5402 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5403 type = IETF_ACK_ECN;
5404 }
5405
5406 if (!writer->WriteUInt8(type)) {
5407 set_detailed_error("No room for frame-type");
5408 return false;
5409 }
5410
5411 QuicPacketNumber largest_acked = LargestAcked(frame);
5412 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5413 set_detailed_error("No room for largest-acked in ack frame");
5414 return false;
5415 }
5416
5417 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5418 if (!frame.ack_delay_time.IsInfinite()) {
5419 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5420 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005421 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005422 }
5423
5424 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5425 set_detailed_error("No room for ack-delay in ack frame");
5426 return false;
5427 }
5428 if (type == IETF_ACK_ECN) {
5429 // Encode the ACK ECN fields
5430 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5431 set_detailed_error("No room for ect_0_count in ack frame");
5432 return false;
5433 }
5434 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5435 set_detailed_error("No room for ect_1_count in ack frame");
5436 return false;
5437 }
5438 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5439 set_detailed_error("No room for ecn_ce_count in ack frame");
5440 return false;
5441 }
5442 }
5443
5444 uint64_t ack_block_count = frame.packets.NumIntervals();
5445 if (ack_block_count == 0) {
5446 // If the QuicAckFrame has no Intervals, then it is interpreted
5447 // as an ack of a single packet at QuicAckFrame.largest_acked.
5448 // The resulting ack will consist of only the frame's
5449 // largest_ack & first_ack_block fields. The first ack block will be 0
5450 // (indicating a single packet) and the ack block_count will be 0.
5451 if (!writer->WriteVarInt62(0)) {
5452 set_detailed_error("No room for ack block count in ack frame");
5453 return false;
5454 }
5455 // size of the first block is 1 packet
5456 if (!writer->WriteVarInt62(0)) {
5457 set_detailed_error("No room for first ack block in ack frame");
5458 return false;
5459 }
5460 return true;
5461 }
5462 // Case 2 or 3
5463 auto itr = frame.packets.rbegin();
5464
5465 QuicPacketNumber ack_block_largest(largest_acked);
5466 QuicPacketNumber ack_block_smallest;
5467 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5468 // If largest_acked + 1 is equal to the Max() of the first Interval
5469 // in the QuicAckFrame then the first Interval is the first ack block of the
5470 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5471 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5472 // the remaining Intervals are encoded in additional ack blocks in the
5473 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5474 // Intervals - 1.
5475 ack_block_smallest = itr->min();
5476 itr++;
5477 ack_block_count--;
5478 } else {
5479 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5480 // the first Interval then it is interpreted as acking a single
5481 // packet at QuicAckFrame.largest_acked, with additional
5482 // Intervals indicating additional ack blocks. The encoding is
5483 // a) The packet's largest_acked is the QuicAckFrame's largest
5484 // acked,
5485 // b) the first ack block size is 0,
5486 // c) The packet's ack_block_count is the number of QuicAckFrame
5487 // Intervals, and
5488 // d) The QuicAckFrame Intervals are encoded in additional ack
5489 // blocks in the packet.
5490 ack_block_smallest = largest_acked;
5491 }
5492
5493 if (!writer->WriteVarInt62(ack_block_count)) {
5494 set_detailed_error("No room for ack block count in ack frame");
5495 return false;
5496 }
5497
5498 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5499 if (!writer->WriteVarInt62(first_ack_block)) {
5500 set_detailed_error("No room for first ack block in ack frame");
5501 return false;
5502 }
5503
5504 // For the remaining QuicAckFrame Intervals, if any
5505 while (ack_block_count != 0) {
5506 uint64_t gap_size = ack_block_smallest - itr->max();
5507 if (!writer->WriteVarInt62(gap_size - 1)) {
5508 set_detailed_error("No room for gap block in ack frame");
5509 return false;
5510 }
5511
5512 uint64_t block_size = itr->max() - itr->min();
5513 if (!writer->WriteVarInt62(block_size - 1)) {
5514 set_detailed_error("No room for nth ack block in ack frame");
5515 return false;
5516 }
5517
5518 ack_block_smallest = itr->min();
5519 itr++;
5520 ack_block_count--;
5521 }
5522 return true;
5523}
5524
5525bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5526 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005527 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005528 return AppendIetfResetStreamFrame(frame, writer);
5529 }
5530 if (!writer->WriteUInt32(frame.stream_id)) {
5531 return false;
5532 }
5533
5534 if (!writer->WriteUInt64(frame.byte_offset)) {
5535 return false;
5536 }
5537
5538 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5539 if (!writer->WriteUInt32(error_code)) {
5540 return false;
5541 }
5542
5543 return true;
5544}
5545
5546bool QuicFramer::AppendConnectionCloseFrame(
5547 const QuicConnectionCloseFrame& frame,
5548 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005549 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005550 return AppendIetfConnectionCloseFrame(frame, writer);
5551 }
fkastenholze9d71a82019-04-09 05:12:13 -07005552 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005553 if (!writer->WriteUInt32(error_code)) {
5554 return false;
5555 }
5556 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5557 return false;
5558 }
5559 return true;
5560}
5561
5562bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5563 QuicDataWriter* writer) {
5564 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5565 if (!writer->WriteUInt32(error_code)) {
5566 return false;
5567 }
5568 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5569 if (!writer->WriteUInt32(stream_id)) {
5570 return false;
5571 }
5572 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5573 return false;
5574 }
5575 return true;
5576}
5577
5578bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5579 QuicDataWriter* writer) {
5580 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5581 if (!writer->WriteUInt32(stream_id)) {
5582 return false;
5583 }
5584 if (!writer->WriteUInt64(frame.byte_offset)) {
5585 return false;
5586 }
5587 return true;
5588}
5589
5590bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5591 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005592 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005593 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5594 return AppendIetfBlockedFrame(frame, writer);
5595 }
5596 return AppendStreamBlockedFrame(frame, writer);
5597 }
5598 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5599 if (!writer->WriteUInt32(stream_id)) {
5600 return false;
5601 }
5602 return true;
5603}
5604
5605bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5606 QuicDataWriter* writer) {
5607 if (frame.num_padding_bytes == 0) {
5608 return false;
5609 }
5610 if (frame.num_padding_bytes < 0) {
5611 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5612 writer->WritePadding();
5613 return true;
5614 }
5615 // Please note, num_padding_bytes includes type byte which has been written.
5616 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5617}
5618
5619bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5620 bool last_frame_in_packet,
5621 QuicDataWriter* writer) {
5622 uint8_t type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5623 : IETF_EXTENSION_MESSAGE;
5624 if (!writer->WriteUInt8(type_byte)) {
5625 return false;
5626 }
5627 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5628 return false;
5629 }
5630 for (const auto& slice : frame.message_data) {
5631 if (!writer->WriteBytes(slice.data(), slice.length())) {
5632 return false;
5633 }
5634 }
5635 return true;
5636}
5637
5638bool QuicFramer::RaiseError(QuicErrorCode error) {
5639 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5640 << " detail: " << detailed_error_;
5641 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005642 if (visitor_) {
5643 visitor_->OnError(this);
5644 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005645 return false;
5646}
5647
5648bool QuicFramer::IsVersionNegotiation(
5649 const QuicPacketHeader& header,
5650 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005651 if (!packet_has_ietf_packet_header &&
5652 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005653 return header.version_flag;
5654 }
5655 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5656 return false;
5657 }
5658 return header.long_packet_type == VERSION_NEGOTIATION;
5659}
5660
QUICHE teama6ef0a62019-03-07 20:34:33 -05005661bool QuicFramer::AppendIetfConnectionCloseFrame(
5662 const QuicConnectionCloseFrame& frame,
5663 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005664 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5665 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5666 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5667 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5668 return false;
5669 }
5670
fkastenholzd57d3f92019-07-16 09:05:17 -07005671 uint64_t close_code = 0;
5672 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5673 close_code = static_cast<uint64_t>(frame.transport_error_code);
5674 } else if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5675 close_code = static_cast<uint64_t>(frame.application_error_code);
5676 }
5677
5678 if (!writer->WriteVarInt62(close_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005679 set_detailed_error("Can not write connection close frame error code");
5680 return false;
5681 }
fkastenholze9d71a82019-04-09 05:12:13 -07005682
fkastenholz72f509b2019-04-10 09:17:49 -07005683 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5684 // Write the frame-type of the frame causing the error only
5685 // if it's a CONNECTION_CLOSE/Transport.
5686 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5687 set_detailed_error("Writing frame type failed.");
5688 return false;
5689 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005690 }
5691
fkastenholz72f509b2019-04-10 09:17:49 -07005692 // TODO(fkastenholz): For full IETF CONNECTION CLOSE support,
5693 // if this is a Transport CONNECTION_CLOSE and the extended
5694 // error is not QUIC_IETF_GQUIC_ERROR_MISSING then append the extended
5695 // "QuicErrorCode: #" string to the phrase.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005696 if (!writer->WriteStringPieceVarInt62(
5697 TruncateErrorString(frame.error_details))) {
5698 set_detailed_error("Can not write connection close phrase");
5699 return false;
5700 }
5701 return true;
5702}
5703
QUICHE teama6ef0a62019-03-07 20:34:33 -05005704bool QuicFramer::ProcessIetfConnectionCloseFrame(
5705 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005706 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005707 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005708 frame->close_type = type;
fkastenholzd57d3f92019-07-16 09:05:17 -07005709 uint64_t error_code;
5710 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005711 set_detailed_error("Unable to read connection close error code.");
5712 return false;
5713 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005714
fkastenholzd57d3f92019-07-16 09:05:17 -07005715 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5716 if (error_code > 0xffff) {
5717 frame->transport_error_code =
5718 static_cast<QuicIetfTransportErrorCodes>(0xffff);
5719 QUIC_DLOG(ERROR) << "Transport error code " << error_code << " > 0xffff";
5720 } else {
5721 frame->transport_error_code =
5722 static_cast<QuicIetfTransportErrorCodes>(error_code);
5723 }
5724 } else if (frame->close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5725 if (error_code > 0xffff) {
5726 frame->application_error_code = 0xffff;
5727 QUIC_DLOG(ERROR) << "Application error code " << error_code
5728 << " > 0xffff";
5729 } else {
5730 frame->application_error_code = static_cast<uint16_t>(error_code);
5731 }
5732 }
fkastenholz72f509b2019-04-10 09:17:49 -07005733 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5734 // The frame-type of the frame causing the error is present only
5735 // if it's a CONNECTION_CLOSE/Transport.
5736 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5737 set_detailed_error("Unable to read connection close frame type.");
5738 return false;
5739 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005740 }
5741
5742 uint64_t phrase_length;
5743 if (!reader->ReadVarInt62(&phrase_length)) {
5744 set_detailed_error("Unable to read connection close error details.");
5745 return false;
5746 }
5747 QuicStringPiece phrase;
5748 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5749 set_detailed_error("Unable to read connection close error details.");
5750 return false;
5751 }
fkastenholz72f509b2019-04-10 09:17:49 -07005752 // TODO(fkastenholz): when full support is done, add code here
5753 // to extract the extended error code from the reason phrase
5754 // and set it into frame->extracted_error_code.
vasilvvc48c8712019-03-11 13:38:16 -07005755 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005756
5757 return true;
5758}
5759
5760// IETF Quic Path Challenge/Response frames.
5761bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5762 QuicPathChallengeFrame* frame) {
5763 if (!reader->ReadBytes(frame->data_buffer.data(),
5764 frame->data_buffer.size())) {
5765 set_detailed_error("Can not read path challenge data.");
5766 return false;
5767 }
5768 return true;
5769}
5770
5771bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5772 QuicPathResponseFrame* frame) {
5773 if (!reader->ReadBytes(frame->data_buffer.data(),
5774 frame->data_buffer.size())) {
5775 set_detailed_error("Can not read path response data.");
5776 return false;
5777 }
5778 return true;
5779}
5780
5781bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5782 QuicDataWriter* writer) {
5783 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5784 set_detailed_error("Writing Path Challenge data failed.");
5785 return false;
5786 }
5787 return true;
5788}
5789
5790bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5791 QuicDataWriter* writer) {
5792 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5793 set_detailed_error("Writing Path Response data failed.");
5794 return false;
5795 }
5796 return true;
5797}
5798
5799// Add a new ietf-format stream reset frame.
5800// General format is
5801// stream id
5802// application error code
5803// final offset
5804bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5805 QuicDataWriter* writer) {
5806 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5807 set_detailed_error("Writing reset-stream stream id failed.");
5808 return false;
5809 }
fkastenholz07300e52019-07-16 11:51:37 -07005810 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005811 set_detailed_error("Writing reset-stream error code failed.");
5812 return false;
5813 }
5814 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5815 set_detailed_error("Writing reset-stream final-offset failed.");
5816 return false;
5817 }
5818 return true;
5819}
5820
5821bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5822 QuicRstStreamFrame* frame) {
5823 // Get Stream ID from frame. ReadVarIntStreamID returns false
5824 // if either A) there is a read error or B) the resulting value of
5825 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005826 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005827 set_detailed_error("Unable to read rst stream stream id.");
5828 return false;
5829 }
5830
fkastenholz07300e52019-07-16 11:51:37 -07005831 uint64_t error_code;
5832 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005833 set_detailed_error("Unable to read rst stream error code.");
5834 return false;
5835 }
fkastenholz07300e52019-07-16 11:51:37 -07005836 if (error_code > 0xffff) {
5837 frame->ietf_error_code = 0xffff;
5838 QUIC_DLOG(ERROR) << "Reset stream error code (" << error_code
5839 << ") > 0xffff";
5840 } else {
5841 frame->ietf_error_code = static_cast<uint16_t>(error_code);
5842 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005843
5844 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5845 set_detailed_error("Unable to read rst stream sent byte offset.");
5846 return false;
5847 }
5848 return true;
5849}
5850
5851bool QuicFramer::ProcessStopSendingFrame(
5852 QuicDataReader* reader,
5853 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005854 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005855 set_detailed_error("Unable to read stop sending stream id.");
5856 return false;
5857 }
5858
fkastenholz733552e2019-07-16 11:16:58 -07005859 uint64_t error_code;
5860 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005861 set_detailed_error("Unable to read stop sending application error code.");
5862 return false;
5863 }
fkastenholz733552e2019-07-16 11:16:58 -07005864 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5865 if (error_code > 0xffff) {
5866 stop_sending_frame->application_error_code = 0xffff;
5867 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5868 << ") > 0xffff";
5869 } else {
5870 stop_sending_frame->application_error_code =
5871 static_cast<uint16_t>(error_code);
5872 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005873 return true;
5874}
5875
5876bool QuicFramer::AppendStopSendingFrame(
5877 const QuicStopSendingFrame& stop_sending_frame,
5878 QuicDataWriter* writer) {
5879 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5880 set_detailed_error("Can not write stop sending stream id");
5881 return false;
5882 }
fkastenholz733552e2019-07-16 11:16:58 -07005883 if (!writer->WriteVarInt62(
5884 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005885 set_detailed_error("Can not write application error code");
5886 return false;
5887 }
5888 return true;
5889}
5890
5891// Append/process IETF-Format MAX_DATA Frame
5892bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5893 QuicDataWriter* writer) {
5894 if (!writer->WriteVarInt62(frame.byte_offset)) {
5895 set_detailed_error("Can not write MAX_DATA byte-offset");
5896 return false;
5897 }
5898 return true;
5899}
5900
5901bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5902 QuicWindowUpdateFrame* frame) {
5903 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5904 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5905 set_detailed_error("Can not read MAX_DATA byte-offset");
5906 return false;
5907 }
5908 return true;
5909}
5910
5911// Append/process IETF-Format MAX_STREAM_DATA Frame
5912bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5913 QuicDataWriter* writer) {
5914 if (!writer->WriteVarInt62(frame.stream_id)) {
5915 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5916 return false;
5917 }
5918 if (!writer->WriteVarInt62(frame.byte_offset)) {
5919 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5920 return false;
5921 }
5922 return true;
5923}
5924
5925bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5926 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005927 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005928 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5929 return false;
5930 }
5931 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5932 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5933 return false;
5934 }
5935 return true;
5936}
5937
fkastenholz3c4eabf2019-04-22 07:49:59 -07005938bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005939 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005940 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005941 set_detailed_error("Can not write MAX_STREAMS stream count");
5942 return false;
5943 }
5944 return true;
5945}
5946
5947bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005948 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005949 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005950 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005951 set_detailed_error("Can not read MAX_STREAMS stream count.");
5952 return false;
5953 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005954 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
5955 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005956}
5957
5958bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
5959 QuicDataWriter* writer) {
5960 if (!writer->WriteVarInt62(frame.offset)) {
5961 set_detailed_error("Can not write blocked offset.");
5962 return false;
5963 }
5964 return true;
5965}
5966
5967bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
5968 QuicBlockedFrame* frame) {
5969 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
5970 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5971 if (!reader->ReadVarInt62(&frame->offset)) {
5972 set_detailed_error("Can not read blocked offset.");
5973 return false;
5974 }
5975 return true;
5976}
5977
5978bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
5979 QuicDataWriter* writer) {
5980 if (!writer->WriteVarInt62(frame.stream_id)) {
5981 set_detailed_error("Can not write stream blocked stream id.");
5982 return false;
5983 }
5984 if (!writer->WriteVarInt62(frame.offset)) {
5985 set_detailed_error("Can not write stream blocked offset.");
5986 return false;
5987 }
5988 return true;
5989}
5990
5991bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
5992 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005993 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005994 set_detailed_error("Can not read stream blocked stream id.");
5995 return false;
5996 }
5997 if (!reader->ReadVarInt62(&frame->offset)) {
5998 set_detailed_error("Can not read stream blocked offset.");
5999 return false;
6000 }
6001 return true;
6002}
6003
fkastenholz3c4eabf2019-04-22 07:49:59 -07006004bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6005 QuicDataWriter* writer) {
6006 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006007 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6008 return false;
6009 }
6010 return true;
6011}
6012
6013bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006014 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006015 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006016 if (!reader->ReadVarIntU32(&frame->stream_count)) {
6017 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006018 return false;
6019 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006020 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
6021
QUICHE teama6ef0a62019-03-07 20:34:33 -05006022 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
6023 // frame is implemented and passed up to the stream ID manager.
fkastenholz3c4eabf2019-04-22 07:49:59 -07006024 if (frame->stream_count >
6025 QuicUtils::GetMaxStreamCount(
6026 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
6027 ((perspective_ == Perspective::IS_CLIENT)
6028 ? Perspective::IS_SERVER
6029 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006030 // If stream count is such that the resulting stream ID would exceed our
6031 // implementation limit, generate an error.
6032 set_detailed_error(
6033 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6034 return false;
6035 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006036 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006037}
6038
6039bool QuicFramer::AppendNewConnectionIdFrame(
6040 const QuicNewConnectionIdFrame& frame,
6041 QuicDataWriter* writer) {
6042 if (!writer->WriteVarInt62(frame.sequence_number)) {
6043 set_detailed_error("Can not write New Connection ID sequence number");
6044 return false;
6045 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006046 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6047 set_detailed_error("Can not write New Connection ID retire_prior_to");
6048 return false;
6049 }
dschinazicf5b1e22019-07-17 18:35:17 -07006050 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006051 set_detailed_error("Can not write New Connection ID frame connection ID");
6052 return false;
6053 }
6054
6055 if (!writer->WriteBytes(
6056 static_cast<const void*>(&frame.stateless_reset_token),
6057 sizeof(frame.stateless_reset_token))) {
6058 set_detailed_error("Can not write New Connection ID Reset Token");
6059 return false;
6060 }
6061 return true;
6062}
6063
6064bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6065 QuicNewConnectionIdFrame* frame) {
6066 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6067 set_detailed_error(
6068 "Unable to read new connection ID frame sequence number.");
6069 return false;
6070 }
6071
fkastenholz1c19fc22019-07-12 11:06:19 -07006072 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6073 set_detailed_error(
6074 "Unable to read new connection ID frame retire_prior_to.");
6075 return false;
6076 }
6077 if (frame->retire_prior_to > frame->sequence_number) {
6078 set_detailed_error("Retire_prior_to > sequence_number.");
6079 return false;
6080 }
dschinazicf5b1e22019-07-17 18:35:17 -07006081
6082 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6083 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006084 return false;
6085 }
6086
dschinazicf5b1e22019-07-17 18:35:17 -07006087 if (frame->connection_id.length() > kQuicMaxConnectionIdLength) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006088 set_detailed_error("New connection ID length too high.");
6089 return false;
6090 }
6091
dschinazicf5b1e22019-07-17 18:35:17 -07006092 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6093 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006094 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006095 return false;
6096 }
6097
QUICHE teama6ef0a62019-03-07 20:34:33 -05006098 if (!reader->ReadBytes(&frame->stateless_reset_token,
6099 sizeof(frame->stateless_reset_token))) {
6100 set_detailed_error("Can not read new connection ID frame reset token.");
6101 return false;
6102 }
6103 return true;
6104}
6105
6106bool QuicFramer::AppendRetireConnectionIdFrame(
6107 const QuicRetireConnectionIdFrame& frame,
6108 QuicDataWriter* writer) {
6109 if (!writer->WriteVarInt62(frame.sequence_number)) {
6110 set_detailed_error("Can not write Retire Connection ID sequence number");
6111 return false;
6112 }
6113 return true;
6114}
6115
6116bool QuicFramer::ProcessRetireConnectionIdFrame(
6117 QuicDataReader* reader,
6118 QuicRetireConnectionIdFrame* frame) {
6119 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6120 set_detailed_error(
6121 "Unable to read retire connection ID frame sequence number.");
6122 return false;
6123 }
6124 return true;
6125}
6126
6127uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6128 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006129 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006130 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6131 }
6132 uint8_t type_byte = 0;
6133 // Fin bit.
6134 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6135
6136 // Data Length bit.
6137 type_byte <<= kQuicStreamDataLengthShift;
6138 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6139
6140 // Offset 3 bits.
6141 type_byte <<= kQuicStreamShift;
6142 const size_t offset_len =
6143 GetStreamOffsetSize(version_.transport_version, frame.offset);
6144 if (offset_len > 0) {
6145 type_byte |= offset_len - 1;
6146 }
6147
6148 // stream id 2 bits.
6149 type_byte <<= kQuicStreamIdShift;
6150 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6151 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6152
6153 return type_byte;
6154}
6155
6156uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6157 const QuicStreamFrame& frame,
6158 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006159 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006160 uint8_t type_byte = IETF_STREAM;
6161 if (!last_frame_in_packet) {
6162 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6163 }
6164 if (frame.offset != 0) {
6165 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6166 }
6167 if (frame.fin) {
6168 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6169 }
6170 return type_byte;
6171}
6172
6173void QuicFramer::InferPacketHeaderTypeFromVersion() {
6174 // This function should only be called when server connection negotiates the
6175 // version.
6176 DCHECK(perspective_ == Perspective::IS_SERVER &&
6177 !infer_packet_header_type_from_version_);
6178 infer_packet_header_type_from_version_ = true;
6179}
6180
QUICHE team10b22a12019-03-21 15:31:42 -07006181void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6182 if (supports_multiple_packet_number_spaces_) {
6183 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6184 return;
6185 }
6186 if (largest_packet_number_.IsInitialized()) {
6187 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6188 "packet has been received.";
6189 return;
6190 }
6191
6192 supports_multiple_packet_number_spaces_ = true;
6193}
6194
fayangccbab732019-05-13 10:11:25 -07006195// static
6196QuicErrorCode QuicFramer::ProcessPacketDispatcher(
6197 const QuicEncryptedPacket& packet,
dschinazib42a8c52019-05-30 09:45:01 -07006198 uint8_t expected_destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07006199 PacketHeaderFormat* format,
6200 bool* version_flag,
6201 QuicVersionLabel* version_label,
fayangccbab732019-05-13 10:11:25 -07006202 QuicConnectionId* destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006203 QuicConnectionId* source_connection_id,
fayangccbab732019-05-13 10:11:25 -07006204 std::string* detailed_error) {
6205 QuicDataReader reader(packet.data(), packet.length());
6206
dschinazib42a8c52019-05-30 09:45:01 -07006207 *source_connection_id = EmptyQuicConnectionId();
fayangccbab732019-05-13 10:11:25 -07006208 uint8_t first_byte;
6209 if (!reader.ReadBytes(&first_byte, 1)) {
6210 *detailed_error = "Unable to read first byte.";
6211 return QUIC_INVALID_PACKET_HEADER;
6212 }
dschinazib42a8c52019-05-30 09:45:01 -07006213 uint8_t destination_connection_id_length = 0, source_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006214 if (!QuicUtils::IsIetfPacketHeader(first_byte)) {
6215 *format = GOOGLE_QUIC_PACKET;
6216 *version_flag = (first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
dschinazib42a8c52019-05-30 09:45:01 -07006217 destination_connection_id_length =
fayangccbab732019-05-13 10:11:25 -07006218 first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
dschinazib42a8c52019-05-30 09:45:01 -07006219 if (destination_connection_id_length == 0 ||
fayangccbab732019-05-13 10:11:25 -07006220 !reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006221 destination_connection_id_length)) {
fayangccbab732019-05-13 10:11:25 -07006222 *detailed_error = "Unable to read ConnectionId.";
6223 return QUIC_INVALID_PACKET_HEADER;
6224 }
6225 if (*version_flag && !ProcessVersionLabel(&reader, version_label)) {
6226 *detailed_error = "Unable to read protocol version.";
6227 return QUIC_INVALID_PACKET_HEADER;
6228 }
6229 return QUIC_NO_ERROR;
6230 }
6231
6232 *format = GetIetfPacketHeaderFormat(first_byte);
6233 QUIC_DVLOG(1) << "Dispatcher: Processing IETF QUIC packet, format: "
6234 << *format;
6235 *version_flag = *format == IETF_QUIC_LONG_HEADER_PACKET;
6236 if (*format == IETF_QUIC_LONG_HEADER_PACKET) {
6237 if (!ProcessVersionLabel(&reader, version_label)) {
6238 *detailed_error = "Unable to read protocol version.";
6239 return QUIC_INVALID_PACKET_HEADER;
6240 }
dschinazi8ff74822019-05-28 16:37:20 -07006241 // Set should_update_expected_server_connection_id_length to true to bypass
fayangccbab732019-05-13 10:11:25 -07006242 // connection ID lengths validation.
dschinazi8ff74822019-05-28 16:37:20 -07006243 uint8_t unused_expected_server_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006244 if (!ProcessAndValidateIetfConnectionIdLength(
6245 &reader, ParseQuicVersionLabel(*version_label),
dschinazi334f0232019-05-29 16:08:53 -07006246 Perspective::IS_SERVER,
dschinazi8ff74822019-05-28 16:37:20 -07006247 /*should_update_expected_server_connection_id_length=*/true,
6248 &unused_expected_server_connection_id_length,
dschinazib42a8c52019-05-30 09:45:01 -07006249 &destination_connection_id_length, &source_connection_id_length,
6250 detailed_error)) {
fayangccbab732019-05-13 10:11:25 -07006251 return QUIC_INVALID_PACKET_HEADER;
6252 }
6253 } else {
dschinazib42a8c52019-05-30 09:45:01 -07006254 // For short header packets, expected_destination_connection_id_length
6255 // is used to determine the destination_connection_id_length.
6256 destination_connection_id_length =
6257 expected_destination_connection_id_length;
6258 DCHECK_EQ(0, source_connection_id_length);
fayangccbab732019-05-13 10:11:25 -07006259 }
6260 // Read destination connection ID.
6261 if (!reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006262 destination_connection_id_length)) {
6263 *detailed_error = "Unable to read destination connection ID.";
6264 return QUIC_INVALID_PACKET_HEADER;
6265 }
6266 // Read source connection ID.
6267 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
6268 !reader.ReadConnectionId(source_connection_id,
6269 source_connection_id_length)) {
6270 *detailed_error = "Unable to read source connection ID.";
fayangccbab732019-05-13 10:11:25 -07006271 return QUIC_INVALID_PACKET_HEADER;
6272 }
6273 return QUIC_NO_ERROR;
6274}
6275
dschinazide0f6dc2019-05-15 16:10:11 -07006276// static
6277bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6278 char* packet_bytes,
6279 QuicByteCount packet_length,
6280 const char* destination_connection_id_bytes,
6281 uint8_t destination_connection_id_length) {
6282 if (packet_bytes == nullptr) {
6283 QUIC_BUG << "Invalid packet_bytes";
6284 return false;
6285 }
6286 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6287 packet_length > 65535) {
6288 QUIC_BUG << "Invalid packet_length";
6289 return false;
6290 }
6291 if (destination_connection_id_length > kQuicMaxConnectionIdLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006292 destination_connection_id_length <
6293 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006294 QUIC_BUG << "Invalid connection_id_length";
6295 return false;
6296 }
6297 // clang-format off
6298 static const unsigned char packet_start_bytes[] = {
6299 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6300 0xc0,
6301 // Version, part of the IETF space reserved for negotiation.
6302 // This intentionally differs from QuicVersionReservedForNegotiation()
6303 // to allow differentiating them over the wire.
6304 0xca, 0xba, 0xda, 0xba,
6305 };
6306 // clang-format on
6307 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6308 QuicDataWriter writer(packet_length, packet_bytes);
6309 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6310 QUIC_BUG << "Failed to write packet start";
6311 return false;
6312 }
6313
6314 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6315 destination_connection_id_length);
6316 if (!AppendIetfConnectionIds(/*version_flag=*/true, destination_connection_id,
6317 EmptyQuicConnectionId(), &writer)) {
6318 QUIC_BUG << "Failed to write connection IDs";
6319 return false;
6320 }
6321 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6322 // not parse with any known version. The zeroes make sure that packet numbers,
6323 // retry token lengths and payload lengths are parsed as zero, and if the
6324 // zeroes are treated as padding frames, 0xff is known to not parse as a
6325 // valid frame type.
6326 if (!writer.WriteUInt64(0) ||
6327 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6328 QUIC_BUG << "Failed to write 18 bytes";
6329 return false;
6330 }
6331 // Make sure the polite greeting below is padded to a 16-byte boundary to
6332 // make it easier to read in tcpdump.
6333 while (writer.length() % 16 != 0) {
6334 if (!writer.WriteUInt8(0)) {
6335 QUIC_BUG << "Failed to write padding byte";
6336 return false;
6337 }
6338 }
6339 // Add a polite greeting in case a human sees this in tcpdump.
6340 static const char polite_greeting[] =
6341 "This packet only exists to trigger IETF QUIC version negotiation. "
6342 "Please respond with a Version Negotiation packet indicating what "
6343 "versions you support. Thank you and have a nice day.";
6344 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6345 QUIC_BUG << "Failed to write polite greeting";
6346 return false;
6347 }
6348 // Fill the rest of the packet with zeroes.
6349 writer.WritePadding();
6350 DCHECK_EQ(0u, writer.remaining());
6351 return true;
6352}
6353
6354// static
6355bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6356 const char* packet_bytes,
6357 QuicByteCount packet_length,
6358 char* source_connection_id_bytes,
6359 uint8_t* source_connection_id_length_out,
6360 std::string* detailed_error) {
6361 if (detailed_error == nullptr) {
6362 QUIC_BUG << "Invalid error_details";
6363 return false;
6364 }
6365 *detailed_error = "";
6366 if (packet_bytes == nullptr) {
6367 *detailed_error = "Invalid packet_bytes";
6368 return false;
6369 }
6370 if (packet_length < 6) {
6371 *detailed_error = "Invalid packet_length";
6372 return false;
6373 }
6374 if (source_connection_id_bytes == nullptr) {
6375 *detailed_error = "Invalid source_connection_id_bytes";
6376 return false;
6377 }
6378 if (source_connection_id_length_out == nullptr) {
6379 *detailed_error = "Invalid source_connection_id_length_out";
6380 return false;
6381 }
6382 QuicDataReader reader(packet_bytes, packet_length);
6383 uint8_t type_byte = 0;
6384 if (!reader.ReadUInt8(&type_byte)) {
6385 *detailed_error = "Failed to read type byte";
6386 return false;
6387 }
6388 if ((type_byte & 0x80) == 0) {
6389 *detailed_error = "Packet does not have long header";
6390 return false;
6391 }
6392 uint32_t version = 0;
6393 if (!reader.ReadUInt32(&version)) {
6394 *detailed_error = "Failed to read version";
6395 return false;
6396 }
6397 if (version != 0) {
6398 *detailed_error = "Packet is not a version negotiation packet";
6399 return false;
6400 }
dschinazi8ff74822019-05-28 16:37:20 -07006401 uint8_t expected_server_connection_id_length = 0,
dschinazide0f6dc2019-05-15 16:10:11 -07006402 destination_connection_id_length = 0, source_connection_id_length = 0;
6403 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07006404 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
dschinazi8ff74822019-05-28 16:37:20 -07006405 /*should_update_expected_server_connection_id_length=*/true,
6406 &expected_server_connection_id_length,
6407 &destination_connection_id_length, &source_connection_id_length,
6408 detailed_error)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006409 return false;
6410 }
6411 if (destination_connection_id_length != 0) {
6412 *detailed_error = "Received unexpected destination connection ID length";
6413 return false;
6414 }
6415 QuicConnectionId destination_connection_id, source_connection_id;
6416 if (!reader.ReadConnectionId(&destination_connection_id,
6417 destination_connection_id_length)) {
6418 *detailed_error = "Failed to read destination connection ID";
6419 return false;
6420 }
6421 if (!reader.ReadConnectionId(&source_connection_id,
6422 source_connection_id_length)) {
6423 *detailed_error = "Failed to read source connection ID";
6424 return false;
6425 }
6426
6427 memcpy(source_connection_id_bytes, source_connection_id.data(),
6428 source_connection_id_length);
6429 *source_connection_id_length_out = source_connection_id_length;
6430
6431 return true;
6432}
6433
QUICHE teama6ef0a62019-03-07 20:34:33 -05006434#undef ENDPOINT // undef for jumbo builds
6435} // namespace quic