blob: 30a3742b0f7f2401eb052fa546184fb5f74246f0 [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>
bnc463f2352019-10-10 04:49:34 -070011#include <utility>
QUICHE teama6ef0a62019-03-07 20:34:33 -050012
13#include "net/third_party/quiche/src/quic/core/crypto/crypto_framer.h"
nharper55fa6132019-05-07 19:37:21 -070014#include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050015#include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake_message.h"
16#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
nharper55fa6132019-05-07 19:37:21 -070017#include "net/third_party/quiche/src/quic/core/crypto/crypto_utils.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050018#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
20#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
21#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
22#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
23#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
24#include "net/third_party/quiche/src/quic/core/quic_constants.h"
25#include "net/third_party/quiche/src/quic/core/quic_data_reader.h"
26#include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
ianswett97b690b2019-05-02 15:12:43 -070027#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
dschinazib953d022019-08-01 18:05:58 -070028#include "net/third_party/quiche/src/quic/core/quic_packets.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050029#include "net/third_party/quiche/src/quic/core/quic_socket_address_coder.h"
30#include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h"
31#include "net/third_party/quiche/src/quic/core/quic_types.h"
32#include "net/third_party/quiche/src/quic/core/quic_utils.h"
33#include "net/third_party/quiche/src/quic/core/quic_versions.h"
34#include "net/third_party/quiche/src/quic/platform/api/quic_aligned.h"
35#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
36#include "net/third_party/quiche/src/quic/platform/api/quic_client_stats.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050037#include "net/third_party/quiche/src/quic/platform/api/quic_fallthrough.h"
38#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
39#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
40#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
41#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050042#include "net/third_party/quiche/src/quic/platform/api/quic_stack_trace.h"
bnc4e9283d2019-12-17 07:08:57 -080043#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
dmcardlecf0bfcf2019-12-13 08:08:21 -080044#include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
45#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
46#include "net/third_party/quiche/src/common/platform/api/quiche_text_utils.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050047
48namespace quic {
49
50namespace {
51
52#define ENDPOINT \
53 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
54
QUICHE teama6ef0a62019-03-07 20:34:33 -050055// Number of bits the packet number length bits are shifted from the right
56// edge of the header.
57const uint8_t kPublicHeaderSequenceNumberShift = 4;
58
59// There are two interpretations for the Frame Type byte in the QUIC protocol,
60// resulting in two Frame Types: Special Frame Types and Regular Frame Types.
61//
62// Regular Frame Types use the Frame Type byte simply. Currently defined
63// Regular Frame Types are:
64// Padding : 0b 00000000 (0x00)
65// ResetStream : 0b 00000001 (0x01)
66// ConnectionClose : 0b 00000010 (0x02)
67// GoAway : 0b 00000011 (0x03)
68// WindowUpdate : 0b 00000100 (0x04)
69// Blocked : 0b 00000101 (0x05)
70//
71// Special Frame Types encode both a Frame Type and corresponding flags
72// all in the Frame Type byte. Currently defined Special Frame Types
73// are:
74// Stream : 0b 1xxxxxxx
75// Ack : 0b 01xxxxxx
76//
77// Semantics of the flag bits above (the x bits) depends on the frame type.
78
79// Masks to determine if the frame type is a special use
80// and for specific special frame types.
81const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000
82const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000
83const uint8_t kQuicFrameTypeStreamMask = 0x80;
84const uint8_t kQuicFrameTypeAckMask = 0x40;
85static_assert(kQuicFrameTypeSpecialMask ==
86 (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask),
87 "Invalid kQuicFrameTypeSpecialMask");
88
89// The stream type format is 1FDOOOSS, where
90// F is the fin bit.
91// D is the data length bit (0 or 2 bytes).
92// OO/OOO are the size of the offset.
93// SS is the size of the stream ID.
94// Note that the stream encoding can not be determined by inspection. It can
95// be determined only by knowing the QUIC Version.
96// Stream frame relative shifts and masks for interpreting the stream flags.
97// StreamID may be 1, 2, 3, or 4 bytes.
98const uint8_t kQuicStreamIdShift = 2;
99const uint8_t kQuicStreamIDLengthMask = 0x03;
100
101// Offset may be 0, 2, 4, or 8 bytes.
102const uint8_t kQuicStreamShift = 3;
103const uint8_t kQuicStreamOffsetMask = 0x07;
104
105// Data length may be 0 or 2 bytes.
106const uint8_t kQuicStreamDataLengthShift = 1;
107const uint8_t kQuicStreamDataLengthMask = 0x01;
108
109// Fin bit may be set or not.
110const uint8_t kQuicStreamFinShift = 1;
111const uint8_t kQuicStreamFinMask = 0x01;
112
113// The format is 01M0LLOO, where
114// M if set, there are multiple ack blocks in the frame.
115// LL is the size of the largest ack field.
116// OO is the size of the ack blocks offset field.
117// packet number size shift used in AckFrames.
118const uint8_t kQuicSequenceNumberLengthNumBits = 2;
119const uint8_t kActBlockLengthOffset = 0;
120const uint8_t kLargestAckedOffset = 2;
121
122// Acks may have only one ack block.
123const uint8_t kQuicHasMultipleAckBlocksOffset = 5;
124
125// Timestamps are 4 bytes followed by 2 bytes.
126const uint8_t kQuicNumTimestampsLength = 1;
127const uint8_t kQuicFirstTimestampLength = 4;
128const uint8_t kQuicTimestampLength = 2;
129// Gaps between packet numbers are 1 byte.
130const uint8_t kQuicTimestampPacketNumberGapLength = 1;
131
132// Maximum length of encoded error strings.
133const int kMaxErrorStringLength = 256;
134
135const uint8_t kConnectionIdLengthAdjustment = 3;
136const uint8_t kDestinationConnectionIdLengthMask = 0xF0;
137const uint8_t kSourceConnectionIdLengthMask = 0x0F;
138
139// Returns the absolute value of the difference between |a| and |b|.
140uint64_t Delta(uint64_t a, uint64_t b) {
141 // Since these are unsigned numbers, we can't just return abs(a - b)
142 if (a < b) {
143 return b - a;
144 }
145 return a - b;
146}
147
148uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) {
149 return (Delta(target, a) < Delta(target, b)) ? a : b;
150}
151
QUICHE teama6ef0a62019-03-07 20:34:33 -0500152QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) {
153 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
154 case PACKET_FLAGS_8BYTE_PACKET:
155 return PACKET_6BYTE_PACKET_NUMBER;
156 case PACKET_FLAGS_4BYTE_PACKET:
157 return PACKET_4BYTE_PACKET_NUMBER;
158 case PACKET_FLAGS_2BYTE_PACKET:
159 return PACKET_2BYTE_PACKET_NUMBER;
160 case PACKET_FLAGS_1BYTE_PACKET:
161 return PACKET_1BYTE_PACKET_NUMBER;
162 default:
163 QUIC_BUG << "Unreachable case statement.";
164 return PACKET_6BYTE_PACKET_NUMBER;
165 }
166}
167
dschinazi17d42422019-06-18 16:35:07 -0700168QuicPacketNumberLength ReadAckPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -0700169 uint8_t flags) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500170 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
171 case PACKET_FLAGS_8BYTE_PACKET:
172 return PACKET_6BYTE_PACKET_NUMBER;
173 case PACKET_FLAGS_4BYTE_PACKET:
174 return PACKET_4BYTE_PACKET_NUMBER;
175 case PACKET_FLAGS_2BYTE_PACKET:
176 return PACKET_2BYTE_PACKET_NUMBER;
177 case PACKET_FLAGS_1BYTE_PACKET:
178 return PACKET_1BYTE_PACKET_NUMBER;
179 default:
180 QUIC_BUG << "Unreachable case statement.";
181 return PACKET_6BYTE_PACKET_NUMBER;
182 }
183}
184
185uint8_t PacketNumberLengthToOnWireValue(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500186 QuicPacketNumberLength packet_number_length) {
fayang36825da2019-08-21 14:01:27 -0700187 return packet_number_length - 1;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500188}
189
fayang36825da2019-08-21 14:01:27 -0700190QuicPacketNumberLength GetShortHeaderPacketNumberLength(uint8_t type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500191 DCHECK(!(type & FLAGS_LONG_HEADER));
fayang36825da2019-08-21 14:01:27 -0700192 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500193}
194
fayang36825da2019-08-21 14:01:27 -0700195uint8_t LongHeaderTypeToOnWireValue(QuicLongHeaderType type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500196 switch (type) {
197 case INITIAL:
fayang36825da2019-08-21 14:01:27 -0700198 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500199 case ZERO_RTT_PROTECTED:
fayang36825da2019-08-21 14:01:27 -0700200 return 1 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500201 case HANDSHAKE:
fayang36825da2019-08-21 14:01:27 -0700202 return 2 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500203 case RETRY:
fayang36825da2019-08-21 14:01:27 -0700204 return 3 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500205 case VERSION_NEGOTIATION:
206 return 0xF0; // Value does not matter
207 default:
208 QUIC_BUG << "Invalid long header type: " << type;
209 return 0xFF;
210 }
211}
212
fayang36825da2019-08-21 14:01:27 -0700213bool GetLongHeaderType(uint8_t type, QuicLongHeaderType* long_header_type) {
214 DCHECK((type & FLAGS_LONG_HEADER));
215 switch ((type & 0x30) >> 4) {
216 case 0:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500217 *long_header_type = INITIAL;
218 break;
fayang36825da2019-08-21 14:01:27 -0700219 case 1:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500220 *long_header_type = ZERO_RTT_PROTECTED;
221 break;
fayang36825da2019-08-21 14:01:27 -0700222 case 2:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500223 *long_header_type = HANDSHAKE;
224 break;
fayang36825da2019-08-21 14:01:27 -0700225 case 3:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500226 *long_header_type = RETRY;
227 break;
228 default:
fayang36825da2019-08-21 14:01:27 -0700229 QUIC_BUG << "Unreachable statement";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500230 *long_header_type = INVALID_PACKET_TYPE;
231 return false;
232 }
233 return true;
234}
235
fayang36825da2019-08-21 14:01:27 -0700236QuicPacketNumberLength GetLongHeaderPacketNumberLength(uint8_t type) {
237 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500238}
239
QUICHE team10b22a12019-03-21 15:31:42 -0700240// Used to get packet number space before packet gets decrypted.
241PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
242 switch (header.form) {
243 case GOOGLE_QUIC_PACKET:
244 QUIC_BUG << "Try to get packet number space of Google QUIC packet";
245 break;
246 case IETF_QUIC_SHORT_HEADER_PACKET:
247 return APPLICATION_DATA;
248 case IETF_QUIC_LONG_HEADER_PACKET:
249 switch (header.long_packet_type) {
250 case INITIAL:
251 return INITIAL_DATA;
252 case HANDSHAKE:
253 return HANDSHAKE_DATA;
254 case ZERO_RTT_PROTECTED:
255 return APPLICATION_DATA;
256 case VERSION_NEGOTIATION:
257 case RETRY:
258 case INVALID_PACKET_TYPE:
259 QUIC_BUG << "Try to get packet number space of long header type: "
260 << QuicUtils::QuicLongHeaderTypetoString(
261 header.long_packet_type);
262 break;
263 }
264 }
265
266 return NUM_PACKET_NUMBER_SPACES;
267}
268
zhongyi546cc452019-04-12 15:27:49 -0700269EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
270 switch (header.form) {
271 case GOOGLE_QUIC_PACKET:
272 QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header";
273 break;
274 case IETF_QUIC_SHORT_HEADER_PACKET:
275 return ENCRYPTION_FORWARD_SECURE;
276 case IETF_QUIC_LONG_HEADER_PACKET:
277 switch (header.long_packet_type) {
278 case INITIAL:
279 return ENCRYPTION_INITIAL;
280 case HANDSHAKE:
281 return ENCRYPTION_HANDSHAKE;
282 case ZERO_RTT_PROTECTED:
283 return ENCRYPTION_ZERO_RTT;
284 case VERSION_NEGOTIATION:
285 case RETRY:
286 case INVALID_PACKET_TYPE:
287 QUIC_BUG << "No encryption used with type "
288 << QuicUtils::QuicLongHeaderTypetoString(
289 header.long_packet_type);
290 }
291 }
292 return NUM_ENCRYPTION_LEVELS;
293}
294
dmcardlecf0bfcf2019-12-13 08:08:21 -0800295quiche::QuicheStringPiece TruncateErrorString(quiche::QuicheStringPiece error) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500296 if (error.length() <= kMaxErrorStringLength) {
297 return error;
298 }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800299 return quiche::QuicheStringPiece(error.data(), kMaxErrorStringLength);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500300}
301
dmcardlecf0bfcf2019-12-13 08:08:21 -0800302size_t TruncatedErrorStringSize(const quiche::QuicheStringPiece& error) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500303 if (error.length() < kMaxErrorStringLength) {
304 return error.length();
305 }
306 return kMaxErrorStringLength;
307}
308
309uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) {
310 if (length == 0) {
311 return 0;
312 }
313 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
314}
315
316bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
317 size_t length = packet_number_length;
318 return length == 1 || length == 2 || length == 4 || length == 6 ||
319 length == 8;
320}
321
322bool IsValidFullPacketNumber(uint64_t full_packet_number,
dschinazi40f0b3d2020-02-19 17:54:05 -0800323 ParsedQuicVersion version) {
324 return full_packet_number > 0 || version.HasIetfQuicFrames();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500325}
326
dschinazi1f485a12019-05-13 11:57:01 -0700327bool AppendIetfConnectionIds(bool version_flag,
dschinazi48ac9192019-07-31 00:07:26 -0700328 bool use_length_prefix,
dschinazi1f485a12019-05-13 11:57:01 -0700329 QuicConnectionId destination_connection_id,
330 QuicConnectionId source_connection_id,
331 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500332 if (!version_flag) {
333 return writer->WriteConnectionId(destination_connection_id);
334 }
335
dschinazi48ac9192019-07-31 00:07:26 -0700336 if (use_length_prefix) {
337 return writer->WriteLengthPrefixedConnectionId(destination_connection_id) &&
338 writer->WriteLengthPrefixedConnectionId(source_connection_id);
339 }
340
QUICHE teama6ef0a62019-03-07 20:34:33 -0500341 // Compute connection ID length byte.
342 uint8_t dcil = GetConnectionIdLengthValue(
343 static_cast<QuicConnectionIdLength>(destination_connection_id.length()));
344 uint8_t scil = GetConnectionIdLengthValue(
345 static_cast<QuicConnectionIdLength>(source_connection_id.length()));
346 uint8_t connection_id_length = dcil << 4 | scil;
347
348 return writer->WriteUInt8(connection_id_length) &&
349 writer->WriteConnectionId(destination_connection_id) &&
350 writer->WriteConnectionId(source_connection_id);
351}
352
353enum class DroppedPacketReason {
354 // General errors
355 INVALID_PUBLIC_HEADER,
356 VERSION_MISMATCH,
357 // Version negotiation packet errors
358 INVALID_VERSION_NEGOTIATION_PACKET,
359 // Public reset packet errors, pre-v44
360 INVALID_PUBLIC_RESET_PACKET,
361 // Data packet errors
362 INVALID_PACKET_NUMBER,
363 INVALID_DIVERSIFICATION_NONCE,
364 DECRYPTION_FAILURE,
365 NUM_REASONS,
366};
367
368void RecordDroppedPacketReason(DroppedPacketReason reason) {
369 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
370 DroppedPacketReason::NUM_REASONS,
371 "The reason a packet was not processed. Recorded "
372 "each time such a packet is dropped");
373}
374
fayangccbab732019-05-13 10:11:25 -0700375PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) {
376 return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
377 : IETF_QUIC_SHORT_HEADER_PACKET;
378}
379
fkastenholzb4dade72019-08-05 06:54:20 -0700380std::string GenerateErrorString(std::string initial_error_string,
381 QuicErrorCode quic_error_code) {
382 if (quic_error_code == QUIC_IETF_GQUIC_ERROR_MISSING) {
383 // QUIC_IETF_GQUIC_ERROR_MISSING is special -- it means not to encode
384 // the error value in the string.
385 return initial_error_string;
386 }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800387 return quiche::QuicheStrCat(
388 std::to_string(static_cast<unsigned>(quic_error_code)), ":",
389 initial_error_string);
fkastenholzb4dade72019-08-05 06:54:20 -0700390}
391
QUICHE teama6ef0a62019-03-07 20:34:33 -0500392} // namespace
393
394QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
395 QuicTime creation_time,
396 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700397 uint8_t expected_server_connection_id_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -0500398 : visitor_(nullptr),
399 error_(QUIC_NO_ERROR),
dschinazi7b9278c2019-05-20 07:36:21 -0700400 last_serialized_server_connection_id_(EmptyQuicConnectionId()),
dschinazi346b7ce2019-06-05 01:38:18 -0700401 last_serialized_client_connection_id_(EmptyQuicConnectionId()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500402 version_(PROTOCOL_UNSUPPORTED, QUIC_VERSION_UNSUPPORTED),
403 supported_versions_(supported_versions),
QUICHE team6987b4a2019-03-15 16:23:04 -0700404 decrypter_level_(ENCRYPTION_INITIAL),
QUICHE team76086e42019-03-25 15:12:29 -0700405 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500406 alternative_decrypter_latch_(false),
407 perspective_(perspective),
408 validate_flags_(true),
409 process_timestamps_(false),
410 creation_time_(creation_time),
411 last_timestamp_(QuicTime::Delta::Zero()),
412 first_sending_packet_number_(FirstSendingPacketNumber()),
413 data_producer_(nullptr),
414 infer_packet_header_type_from_version_(perspective ==
415 Perspective::IS_CLIENT),
dschinazi8ff74822019-05-28 16:37:20 -0700416 expected_server_connection_id_length_(
417 expected_server_connection_id_length),
dschinazi346b7ce2019-06-05 01:38:18 -0700418 expected_client_connection_id_length_(0),
nharper55fa6132019-05-07 19:37:21 -0700419 supports_multiple_packet_number_spaces_(false),
fkastenholz4dc4ba32019-07-30 09:55:25 -0700420 last_written_packet_number_length_(0),
421 peer_ack_delay_exponent_(kDefaultAckDelayExponent),
fkastenholza3660102019-08-28 05:19:24 -0700422 local_ack_delay_exponent_(kDefaultAckDelayExponent),
423 current_received_frame_type_(0) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500424 DCHECK(!supported_versions.empty());
425 version_ = supported_versions_[0];
dschinazi4f95c402020-02-18 13:39:12 -0800426 DCHECK(version_.IsKnown())
dschinazi577b5482020-01-13 15:40:43 -0800427 << ParsedQuicVersionVectorToString(supported_versions_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500428}
429
430QuicFramer::~QuicFramer() {}
431
432// static
433size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
434 QuicStreamId stream_id,
435 QuicStreamOffset offset,
436 bool last_frame_in_packet,
fkastenholzabfd9ec2019-10-31 07:59:12 -0700437 size_t data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700438 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500439 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
440 (last_frame_in_packet
441 ? 0
442 : QuicDataWriter::GetVarInt62Len(data_length)) +
443 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
444 }
445 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
renjietang488201d2019-12-17 13:40:49 -0800446 GetStreamOffsetSize(offset) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500447 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
448}
449
450// static
451size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
452 QuicPacketLength data_length) {
453 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
454 QuicDataWriter::GetVarInt62Len(data_length);
455}
456
457// static
458size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
459 bool last_frame_in_packet,
460 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700461 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500462 << "Try to serialize MESSAGE frame in " << version;
463 return kQuicFrameTypeSize +
464 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
465 length;
466}
467
468// static
fayang43697fd2020-04-21 11:13:43 -0700469size_t QuicFramer::GetMinAckFrameSize(QuicTransportVersion version,
470 const QuicAckFrame& ack_frame,
471 uint32_t local_ack_delay_exponent) {
fkastenholz305e1732019-06-18 05:01:22 -0700472 if (VersionHasIetfQuicFrames(version)) {
fayang91c23d72020-03-09 12:35:05 -0700473 // The minimal ack frame consists of the following fields: Largest
474 // Acknowledged, ACK Delay, 0 ACK Block Count, First ACK Block and ECN
475 // counts.
476 // Type byte + largest acked.
477 size_t min_size =
478 kQuicFrameTypeSize +
479 QuicDataWriter::GetVarInt62Len(LargestAcked(ack_frame).ToUint64());
480 // Ack delay.
481 min_size += QuicDataWriter::GetVarInt62Len(
482 ack_frame.ack_delay_time.ToMicroseconds() >> local_ack_delay_exponent);
483 // 0 ack block count.
484 min_size += QuicDataWriter::GetVarInt62Len(0);
485 // First ack block.
486 min_size += QuicDataWriter::GetVarInt62Len(
487 ack_frame.packets.Empty() ? 0
488 : ack_frame.packets.rbegin()->Length() - 1);
489 // ECN counts.
490 if (ack_frame.ecn_counters_populated &&
491 (ack_frame.ect_0_count || ack_frame.ect_1_count ||
492 ack_frame.ecn_ce_count)) {
493 min_size += (QuicDataWriter::GetVarInt62Len(ack_frame.ect_0_count) +
494 QuicDataWriter::GetVarInt62Len(ack_frame.ect_1_count) +
495 QuicDataWriter::GetVarInt62Len(ack_frame.ecn_ce_count));
496 }
497 return min_size;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500498 }
fayang43697fd2020-04-21 11:13:43 -0700499 return kQuicFrameTypeSize +
500 GetMinPacketNumberLength(LargestAcked(ack_frame)) +
501 kQuicDeltaTimeLargestObservedSize + kQuicNumTimestampsSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500502}
503
504// static
505size_t QuicFramer::GetStopWaitingFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500506 QuicPacketNumberLength packet_number_length) {
507 size_t min_size = kQuicFrameTypeSize + packet_number_length;
508 return min_size;
509}
510
511// static
512size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
513 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700514 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500515 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
516 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700517 kQuicFrameTypeSize +
518 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500519 }
520 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
521 kQuicErrorCodeSize;
522}
523
524// static
fkastenholza037b8b2019-05-07 06:00:05 -0700525size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500526 QuicTransportVersion version,
527 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700528 if (!VersionHasIetfQuicFrames(version)) {
529 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700530 return kQuicFrameTypeSize + kQuicErrorCodeSize +
531 kQuicErrorDetailsLengthSize +
532 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500533 }
fkastenholzb4dade72019-08-05 06:54:20 -0700534
535 // Prepend the extra error information to the string and get the result's
536 // length.
537 const size_t truncated_error_string_size = TruncatedErrorStringSize(
bnc77e77b82020-04-05 10:36:49 -0700538 GenerateErrorString(frame.error_details, frame.quic_error_code));
fkastenholzb4dade72019-08-05 06:54:20 -0700539
fkastenholza037b8b2019-05-07 06:00:05 -0700540 const size_t frame_size =
541 truncated_error_string_size +
542 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholz88d08f42019-09-06 07:38:04 -0700543 kQuicFrameTypeSize +
bnc77e77b82020-04-05 10:36:49 -0700544 QuicDataWriter::GetVarInt62Len(frame.wire_error_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700545 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
546 return frame_size;
547 }
fkastenholzb4dade72019-08-05 06:54:20 -0700548 // The Transport close frame has the transport_close_frame_type, so include
549 // its length.
fkastenholza037b8b2019-05-07 06:00:05 -0700550 return frame_size +
551 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500552}
553
554// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500555size_t QuicFramer::GetMinGoAwayFrameSize() {
556 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
557 kQuicMaxStreamIdSize;
558}
559
560// static
561size_t QuicFramer::GetWindowUpdateFrameSize(
562 QuicTransportVersion version,
563 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700564 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500565 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
566 }
567 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
568 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
renjietangd088eab2019-11-21 14:54:41 -0800569 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500570 }
571 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
572 // fields.
renjietangd088eab2019-11-21 14:54:41 -0800573 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500574 QuicDataWriter::GetVarInt62Len(frame.stream_id);
575}
576
577// static
578size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700579 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700580 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500581 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700582 << ", which does not support IETF Frames, and tried to serialize "
583 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500584 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700585 return kQuicFrameTypeSize +
586 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500587}
588
589// static
590size_t QuicFramer::GetStreamsBlockedFrameSize(
591 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700592 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700593 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500594 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700595 << ", which does not support IETF frames, and tried to serialize "
596 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500597 }
598
fkastenholz3c4eabf2019-04-22 07:49:59 -0700599 return kQuicFrameTypeSize +
600 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500601}
602
603// static
604size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
605 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700606 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500607 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
608 }
609 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
610 // return size of IETF QUIC Blocked frame
611 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
612 }
613 // return size of IETF QUIC Stream Blocked frame.
614 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
615 QuicDataWriter::GetVarInt62Len(frame.stream_id);
616}
617
618// static
619size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
620 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700621 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500622}
623
624// static
625size_t QuicFramer::GetPathChallengeFrameSize(
626 const QuicPathChallengeFrame& frame) {
627 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
628}
629
630// static
631size_t QuicFramer::GetPathResponseFrameSize(
632 const QuicPathResponseFrame& frame) {
633 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
634}
635
636// static
637size_t QuicFramer::GetRetransmittableControlFrameSize(
638 QuicTransportVersion version,
639 const QuicFrame& frame) {
640 switch (frame.type) {
641 case PING_FRAME:
642 // Ping has no payload.
643 return kQuicFrameTypeSize;
644 case RST_STREAM_FRAME:
645 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
646 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700647 return GetConnectionCloseFrameSize(version,
648 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500649 case GOAWAY_FRAME:
650 return GetMinGoAwayFrameSize() +
651 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
652 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700653 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500654 // GetWindowUpdateFrameSize figures this out and returns the correct
655 // length.
656 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
657 case BLOCKED_FRAME:
658 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500659 case NEW_CONNECTION_ID_FRAME:
660 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
661 case RETIRE_CONNECTION_ID_FRAME:
662 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
663 case NEW_TOKEN_FRAME:
664 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700665 case MAX_STREAMS_FRAME:
666 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
667 case STREAMS_BLOCKED_FRAME:
668 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500669 case PATH_RESPONSE_FRAME:
670 return GetPathResponseFrameSize(*frame.path_response_frame);
671 case PATH_CHALLENGE_FRAME:
672 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
673 case STOP_SENDING_FRAME:
674 return GetStopSendingFrameSize(*frame.stop_sending_frame);
fayang01062942020-01-22 07:23:23 -0800675 case HANDSHAKE_DONE_FRAME:
676 // HANDSHAKE_DONE has no payload.
677 return kQuicFrameTypeSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500678
679 case STREAM_FRAME:
680 case ACK_FRAME:
681 case STOP_WAITING_FRAME:
682 case MTU_DISCOVERY_FRAME:
683 case PADDING_FRAME:
684 case MESSAGE_FRAME:
685 case CRYPTO_FRAME:
686 case NUM_FRAME_TYPES:
687 DCHECK(false);
688 return 0;
689 }
690
691 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
692 DCHECK(false);
693 return 0;
694}
695
696// static
697size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
698 // Sizes are 1 through 4 bytes.
699 for (int i = 1; i <= 4; ++i) {
700 stream_id >>= 8;
701 if (stream_id == 0) {
702 return i;
703 }
704 }
705 QUIC_BUG << "Failed to determine StreamIDSize.";
706 return 4;
707}
708
709// static
renjietang488201d2019-12-17 13:40:49 -0800710size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500711 // 0 is a special case.
712 if (offset == 0) {
713 return 0;
714 }
715 // 2 through 8 are the remaining sizes.
716 offset >>= 8;
717 for (int i = 2; i <= 8; ++i) {
718 offset >>= 8;
719 if (offset == 0) {
720 return i;
721 }
722 }
723 QUIC_BUG << "Failed to determine StreamOffsetSize.";
724 return 8;
725}
726
727// static
728size_t QuicFramer::GetNewConnectionIdFrameSize(
729 const QuicNewConnectionIdFrame& frame) {
730 return kQuicFrameTypeSize +
731 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700732 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500733 kConnectionIdLengthSize + frame.connection_id.length() +
734 sizeof(frame.stateless_reset_token);
735}
736
737// static
738size_t QuicFramer::GetRetireConnectionIdFrameSize(
739 const QuicRetireConnectionIdFrame& frame) {
740 return kQuicFrameTypeSize +
741 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
742}
743
744// static
745size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
746 return kQuicFrameTypeSize +
747 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
748 frame.token.length();
749}
750
751// TODO(nharper): Change this method to take a ParsedQuicVersion.
752bool QuicFramer::IsSupportedTransportVersion(
753 const QuicTransportVersion version) const {
754 for (ParsedQuicVersion supported_version : supported_versions_) {
755 if (version == supported_version.transport_version) {
756 return true;
757 }
758 }
759 return false;
760}
761
762bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
763 for (const ParsedQuicVersion& supported_version : supported_versions_) {
764 if (version == supported_version) {
765 return true;
766 }
767 }
768 return false;
769}
770
771size_t QuicFramer::GetSerializedFrameLength(
772 const QuicFrame& frame,
773 size_t free_bytes,
774 bool first_frame,
775 bool last_frame,
776 QuicPacketNumberLength packet_number_length) {
777 // Prevent a rare crash reported in b/19458523.
778 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
779 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
780 << free_bytes << " first_frame:" << first_frame
781 << " last_frame:" << last_frame
782 << " seq num length:" << packet_number_length;
783 set_error(QUIC_INTERNAL_ERROR);
784 visitor_->OnError(this);
785 return 0;
786 }
787 if (frame.type == PADDING_FRAME) {
788 if (frame.padding_frame.num_padding_bytes == -1) {
789 // Full padding to the end of the packet.
790 return free_bytes;
791 } else {
792 // Lite padding.
793 return free_bytes <
794 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
795 ? free_bytes
796 : frame.padding_frame.num_padding_bytes;
797 }
798 }
799
800 size_t frame_len =
801 ComputeFrameLength(frame, last_frame, packet_number_length);
802 if (frame_len <= free_bytes) {
803 // Frame fits within packet. Note that acks may be truncated.
804 return frame_len;
805 }
806 // Only truncate the first frame in a packet, so if subsequent ones go
807 // over, stop including more frames.
808 if (!first_frame) {
809 return 0;
810 }
811 bool can_truncate =
812 frame.type == ACK_FRAME &&
fayang43697fd2020-04-21 11:13:43 -0700813 free_bytes >= GetMinAckFrameSize(version_.transport_version,
814 *frame.ack_frame,
815 local_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500816 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700817 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500818 // Note that we may not use every byte of the writer in this case.
819 QUIC_DLOG(INFO) << ENDPOINT
820 << "Truncating large frame, free bytes: " << free_bytes;
821 return free_bytes;
822 }
823 return 0;
824}
825
826QuicFramer::AckFrameInfo::AckFrameInfo()
827 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
828
829QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
830
831QuicFramer::AckFrameInfo::~AckFrameInfo() {}
832
833bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
834 QuicDataWriter* writer,
835 size_t length_field_offset,
836 EncryptionLevel level) {
837 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
838 !header.version_flag || length_field_offset == 0) {
839 return true;
840 }
841 if (writer->length() < length_field_offset ||
842 writer->length() - length_field_offset <
843 kQuicDefaultLongHeaderLengthLength) {
844 set_detailed_error("Invalid length_field_offset.");
845 QUIC_BUG << "Invalid length_field_offset.";
846 return false;
847 }
848 size_t length_to_write = writer->length() - length_field_offset -
849 kQuicDefaultLongHeaderLengthLength;
850 // Add length of auth tag.
851 length_to_write = GetCiphertextSize(level, length_to_write);
852
853 QuicDataWriter length_writer(writer->length() - length_field_offset,
854 writer->data() + length_field_offset);
855 if (!length_writer.WriteVarInt62(length_to_write,
856 kQuicDefaultLongHeaderLengthLength)) {
857 set_detailed_error("Failed to overwrite long header length.");
858 QUIC_BUG << "Failed to overwrite long header length.";
859 return false;
860 }
861 return true;
862}
863
864size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
865 const QuicFrames& frames,
866 char* buffer,
867 size_t packet_length,
868 EncryptionLevel level) {
dschinaziecad9642019-10-01 10:44:17 -0700869 QUIC_BUG_IF(header.version_flag &&
870 VersionHasIetfInvariantHeader(transport_version()) &&
871 header.long_packet_type == RETRY && !frames.empty())
872 << "IETF RETRY packets cannot contain frames " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500873 QuicDataWriter writer(packet_length, buffer);
874 size_t length_field_offset = 0;
875 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
876 QUIC_BUG << "AppendPacketHeader failed";
877 return 0;
878 }
879
fkastenholz305e1732019-06-18 05:01:22 -0700880 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500881 if (AppendIetfFrames(frames, &writer) == 0) {
882 return 0;
883 }
884 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
885 level)) {
886 return 0;
887 }
888 return writer.length();
889 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500890
891 size_t i = 0;
892 for (const QuicFrame& frame : frames) {
893 // Determine if we should write stream frame length in header.
894 const bool last_frame_in_packet = i == frames.size() - 1;
895 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
896 QUIC_BUG << "AppendTypeByte failed";
897 return 0;
898 }
899
900 switch (frame.type) {
901 case PADDING_FRAME:
902 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
903 QUIC_BUG << "AppendPaddingFrame of "
904 << frame.padding_frame.num_padding_bytes << " failed";
905 return 0;
906 }
907 break;
908 case STREAM_FRAME:
909 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
910 &writer)) {
911 QUIC_BUG << "AppendStreamFrame failed";
912 return 0;
913 }
914 break;
915 case ACK_FRAME:
916 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
917 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
918 return 0;
919 }
920 break;
921 case STOP_WAITING_FRAME:
922 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
923 &writer)) {
924 QUIC_BUG << "AppendStopWaitingFrame failed";
925 return 0;
926 }
927 break;
928 case MTU_DISCOVERY_FRAME:
929 // MTU discovery frames are serialized as ping frames.
930 QUIC_FALLTHROUGH_INTENDED;
931 case PING_FRAME:
932 // Ping has no payload.
933 break;
934 case RST_STREAM_FRAME:
935 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
936 QUIC_BUG << "AppendRstStreamFrame failed";
937 return 0;
938 }
939 break;
940 case CONNECTION_CLOSE_FRAME:
941 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
942 &writer)) {
943 QUIC_BUG << "AppendConnectionCloseFrame failed";
944 return 0;
945 }
946 break;
947 case GOAWAY_FRAME:
948 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
949 QUIC_BUG << "AppendGoAwayFrame failed";
950 return 0;
951 }
952 break;
953 case WINDOW_UPDATE_FRAME:
954 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
955 QUIC_BUG << "AppendWindowUpdateFrame failed";
956 return 0;
957 }
958 break;
959 case BLOCKED_FRAME:
960 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
961 QUIC_BUG << "AppendBlockedFrame failed";
962 return 0;
963 }
964 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500965 case NEW_CONNECTION_ID_FRAME:
966 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700967 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500968 return RaiseError(QUIC_INTERNAL_ERROR);
969 case RETIRE_CONNECTION_ID_FRAME:
970 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700971 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
972 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500973 return RaiseError(QUIC_INTERNAL_ERROR);
974 case NEW_TOKEN_FRAME:
975 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700976 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500977 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700978 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500979 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700980 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500981 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700982 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500983 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700984 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500985 return RaiseError(QUIC_INTERNAL_ERROR);
986 case PATH_RESPONSE_FRAME:
987 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700988 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500989 return RaiseError(QUIC_INTERNAL_ERROR);
990 case PATH_CHALLENGE_FRAME:
991 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700992 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500993 return RaiseError(QUIC_INTERNAL_ERROR);
994 case STOP_SENDING_FRAME:
995 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700996 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500997 return RaiseError(QUIC_INTERNAL_ERROR);
998 case MESSAGE_FRAME:
999 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1000 last_frame_in_packet, &writer)) {
1001 QUIC_BUG << "AppendMessageFrame failed";
1002 return 0;
1003 }
1004 break;
1005 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -07001006 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001007 set_detailed_error(
1008 "Attempt to append CRYPTO frame in version prior to 47.");
1009 return RaiseError(QUIC_INTERNAL_ERROR);
1010 }
1011 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1012 QUIC_BUG << "AppendCryptoFrame failed";
1013 return 0;
1014 }
1015 break;
1016 default:
1017 RaiseError(QUIC_INVALID_FRAME_DATA);
1018 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1019 return 0;
1020 }
1021 ++i;
1022 }
1023
dschinazid1428492019-09-17 23:59:30 -07001024 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) {
1025 return 0;
1026 }
1027
QUICHE teama6ef0a62019-03-07 20:34:33 -05001028 return writer.length();
1029}
1030
1031size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1032 QuicDataWriter* writer) {
1033 size_t i = 0;
1034 for (const QuicFrame& frame : frames) {
1035 // Determine if we should write stream frame length in header.
1036 const bool last_frame_in_packet = i == frames.size() - 1;
1037 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1038 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1039 return 0;
1040 }
1041
1042 switch (frame.type) {
1043 case PADDING_FRAME:
1044 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1045 QUIC_BUG << "AppendPaddingFrame of "
1046 << frame.padding_frame.num_padding_bytes
1047 << " failed: " << detailed_error();
1048 return 0;
1049 }
1050 break;
1051 case STREAM_FRAME:
1052 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1053 writer)) {
1054 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1055 return 0;
1056 }
1057 break;
1058 case ACK_FRAME:
1059 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001060 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1061 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001062 return 0;
1063 }
1064 break;
1065 case STOP_WAITING_FRAME:
1066 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001067 "Attempt to append STOP WAITING frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001068 RaiseError(QUIC_INTERNAL_ERROR);
1069 QUIC_BUG << detailed_error();
1070 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001071 case MTU_DISCOVERY_FRAME:
1072 // MTU discovery frames are serialized as ping frames.
1073 QUIC_FALLTHROUGH_INTENDED;
1074 case PING_FRAME:
1075 // Ping has no payload.
1076 break;
1077 case RST_STREAM_FRAME:
1078 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1079 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1080 return 0;
1081 }
1082 break;
1083 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001084 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1085 writer)) {
1086 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1087 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001088 return 0;
1089 }
1090 break;
1091 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001092 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001093 RaiseError(QUIC_INTERNAL_ERROR);
1094 QUIC_BUG << detailed_error();
1095 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001096 case WINDOW_UPDATE_FRAME:
1097 // Depending on whether there is a stream ID or not, will be either a
1098 // MAX STREAM DATA frame or a MAX DATA frame.
1099 if (frame.window_update_frame->stream_id ==
1100 QuicUtils::GetInvalidStreamId(transport_version())) {
1101 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1102 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1103 return 0;
1104 }
1105 } else {
1106 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1107 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1108 return 0;
1109 }
1110 }
1111 break;
1112 case BLOCKED_FRAME:
1113 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1114 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1115 return 0;
1116 }
1117 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001118 case MAX_STREAMS_FRAME:
1119 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001120 QUIC_BUG << "AppendMaxStreamsFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001121 return 0;
1122 }
1123 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001124 case STREAMS_BLOCKED_FRAME:
1125 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001126 QUIC_BUG << "AppendStreamsBlockedFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001127 return 0;
1128 }
1129 break;
1130 case NEW_CONNECTION_ID_FRAME:
1131 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1132 writer)) {
1133 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1134 return 0;
1135 }
1136 break;
1137 case RETIRE_CONNECTION_ID_FRAME:
1138 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1139 writer)) {
1140 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1141 << detailed_error();
1142 return 0;
1143 }
1144 break;
1145 case NEW_TOKEN_FRAME:
1146 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1147 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1148 return 0;
1149 }
1150 break;
1151 case STOP_SENDING_FRAME:
1152 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1153 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1154 return 0;
1155 }
1156 break;
1157 case PATH_CHALLENGE_FRAME:
1158 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1159 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1160 return 0;
1161 }
1162 break;
1163 case PATH_RESPONSE_FRAME:
1164 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1165 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1166 return 0;
1167 }
1168 break;
1169 case MESSAGE_FRAME:
1170 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1171 last_frame_in_packet, writer)) {
1172 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1173 return 0;
1174 }
1175 break;
1176 case CRYPTO_FRAME:
1177 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1178 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1179 return 0;
1180 }
1181 break;
fayang01062942020-01-22 07:23:23 -08001182 case HANDSHAKE_DONE_FRAME:
1183 // HANDSHAKE_DONE has no payload.
1184 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001185 default:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001186 set_detailed_error("Tried to append unknown frame type.");
dschinazi4a64ab62019-10-01 12:54:00 -07001187 RaiseError(QUIC_INVALID_FRAME_DATA);
1188 QUIC_BUG << "QUIC_INVALID_FRAME_DATA: " << frame.type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001189 return 0;
1190 }
1191 ++i;
1192 }
1193
1194 return writer->length();
1195}
1196
QUICHE teama6ef0a62019-03-07 20:34:33 -05001197// static
1198std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1199 const QuicPublicResetPacket& packet) {
1200 CryptoHandshakeMessage reset;
1201 reset.set_tag(kPRST);
1202 reset.SetValue(kRNON, packet.nonce_proof);
1203 if (packet.client_address.host().address_family() !=
1204 IpAddressFamily::IP_UNSPEC) {
1205 // packet.client_address is non-empty.
1206 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001207 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001208 if (serialized_address.empty()) {
1209 return nullptr;
1210 }
1211 reset.SetStringPiece(kCADR, serialized_address);
1212 }
1213 if (!packet.endpoint_id.empty()) {
1214 reset.SetStringPiece(kEPID, packet.endpoint_id);
1215 }
1216 const QuicData& reset_serialized = reset.GetSerialized();
1217
1218 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1219 reset_serialized.length();
1220 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001221 QuicDataWriter writer(len, buffer.get());
1222
1223 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1224 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1225 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1226 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1227 if (!writer.WriteUInt8(flags)) {
1228 return nullptr;
1229 }
1230
1231 if (!writer.WriteConnectionId(packet.connection_id)) {
1232 return nullptr;
1233 }
1234
1235 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1236 return nullptr;
1237 }
1238
vasilvv0fc587f2019-09-06 13:33:08 -07001239 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001240}
1241
1242// static
1243std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001244 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001245 QuicUint128 stateless_reset_token) {
1246 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1247 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1248 sizeof(stateless_reset_token);
1249 std::unique_ptr<char[]> buffer(new char[len]);
1250 QuicDataWriter writer(len, buffer.get());
1251
1252 uint8_t type = 0;
1253 type |= FLAGS_FIXED_BIT;
1254 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1255 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayang36825da2019-08-21 14:01:27 -07001256 type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001257
1258 // Append type byte.
1259 if (!writer.WriteUInt8(type)) {
1260 return nullptr;
1261 }
1262 // Append random bytes.
1263 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1264 kMinRandomBytesLengthInStatelessReset)) {
1265 return nullptr;
1266 }
1267
1268 // Append stateless reset token.
1269 if (!writer.WriteBytes(&stateless_reset_token,
1270 sizeof(stateless_reset_token))) {
1271 return nullptr;
1272 }
vasilvv0fc587f2019-09-06 13:33:08 -07001273 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001274}
1275
1276// static
1277std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001278 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001279 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001280 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001281 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001282 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001283 ParsedQuicVersionVector wire_versions = versions;
dschinazi5fc6d0c2019-11-26 16:22:05 -08001284 // Add a version reserved for negotiation as suggested by the
1285 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1286 if (wire_versions.empty()) {
1287 // Ensure that version negotiation packets we send have at least two
1288 // versions. This guarantees that, under all circumstances, all QUIC
1289 // packets we send are at least 14 bytes long.
1290 wire_versions = {QuicVersionReservedForNegotiation(),
1291 QuicVersionReservedForNegotiation()};
dschinazi1ac22cc2019-06-25 11:47:50 -07001292 } else {
dschinazi5fc6d0c2019-11-26 16:22:05 -08001293 // This is not uniformely distributed but is acceptable since no security
1294 // depends on this randomness.
1295 size_t version_index = 0;
1296 const bool disable_randomness =
1297 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1298 if (!disable_randomness) {
1299 version_index =
1300 QuicRandom::GetInstance()->RandUint64() % (wire_versions.size() + 1);
dschinazi1ac22cc2019-06-25 11:47:50 -07001301 }
dschinazi5fc6d0c2019-11-26 16:22:05 -08001302 wire_versions.insert(wire_versions.begin() + version_index,
1303 QuicVersionReservedForNegotiation());
dschinazi1ac22cc2019-06-25 11:47:50 -07001304 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001305 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001306 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001307 use_length_prefix, server_connection_id, client_connection_id,
1308 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001309 }
dschinazib417d602019-05-29 13:08:45 -07001310
1311 // The GQUIC encoding does not support encoding client connection IDs.
1312 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001313 // The GQUIC encoding does not support length-prefixed connection IDs.
1314 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001315
dschinazi1ac22cc2019-06-25 11:47:50 -07001316 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001317 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001318 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001319 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001320 QuicDataWriter writer(len, buffer.get());
1321
1322 uint8_t flags = static_cast<uint8_t>(
1323 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
QUICHE teama6ef0a62019-03-07 20:34:33 -05001324 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1325 if (!writer.WriteUInt8(flags)) {
1326 return nullptr;
1327 }
1328
dschinazi8ff74822019-05-28 16:37:20 -07001329 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001330 return nullptr;
1331 }
1332
dschinazi1ac22cc2019-06-25 11:47:50 -07001333 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001334 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001335 return nullptr;
1336 }
1337 }
1338
vasilvv0fc587f2019-09-06 13:33:08 -07001339 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001340}
1341
1342// static
1343std::unique_ptr<QuicEncryptedPacket>
1344QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001345 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001346 QuicConnectionId server_connection_id,
1347 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001348 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001349 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1350 << (use_length_prefix ? "" : "out")
1351 << " length prefix, server_connection_id "
1352 << server_connection_id << " client_connection_id "
1353 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001354 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001355 DCHECK(!versions.empty());
1356 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001357 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001358 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001359 if (use_length_prefix) {
1360 // When using length-prefixed connection IDs, packets carry two lengths
1361 // instead of one.
1362 len += kConnectionIdLengthSize;
1363 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001364 std::unique_ptr<char[]> buffer(new char[len]);
1365 QuicDataWriter writer(len, buffer.get());
1366
1367 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001368 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001369 if (!writer.WriteUInt8(type)) {
1370 return nullptr;
1371 }
1372
1373 if (!writer.WriteUInt32(0)) {
1374 return nullptr;
1375 }
1376
dschinazi48ac9192019-07-31 00:07:26 -07001377 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1378 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001379 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001380 }
1381
1382 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001383 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001384 return nullptr;
1385 }
1386 }
1387
vasilvv0fc587f2019-09-06 13:33:08 -07001388 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001389}
1390
1391bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1392 QuicDataReader reader(packet.data(), packet.length());
1393
1394 bool packet_has_ietf_packet_header = false;
1395 if (infer_packet_header_type_from_version_) {
1396 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001397 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001398 } else if (!reader.IsDoneReading()) {
1399 uint8_t type = reader.PeekByte();
1400 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1401 }
1402 if (packet_has_ietf_packet_header) {
1403 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1404 }
1405
1406 visitor_->OnPacket();
1407
1408 QuicPacketHeader header;
1409 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1410 DCHECK_NE("", detailed_error_);
1411 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1412 << detailed_error_;
1413 DCHECK_NE("", detailed_error_);
1414 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1415 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1416 }
1417
1418 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1419 // The visitor suppresses further processing of the packet.
1420 return true;
1421 }
1422
dschinazie0df3f72019-05-06 16:37:51 -07001423 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001424 if (perspective_ == Perspective::IS_CLIENT) {
1425 QUIC_DVLOG(1) << "Client received version negotiation packet";
1426 return ProcessVersionNegotiationPacket(&reader, header);
1427 } else {
1428 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1429 set_detailed_error("Server received version negotiation packet.");
1430 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1431 }
dschinazie0df3f72019-05-06 16:37:51 -07001432 }
1433
1434 if (header.version_flag && header.version != version_) {
1435 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001436 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001437 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1438 return true;
1439 }
1440 } else {
1441 // A client received a packet of a different version but that packet is
1442 // not a version negotiation packet. It is therefore invalid and dropped.
1443 QUIC_DLOG(ERROR) << "Client received unexpected version "
1444 << ParsedQuicVersionToString(header.version)
1445 << " instead of " << ParsedQuicVersionToString(version_);
1446 set_detailed_error("Client received unexpected version.");
1447 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001448 }
1449 }
1450
1451 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001452 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001453 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001454 } else if (header.reset_flag) {
1455 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001456 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001457 // The optimized decryption algorithm implementations run faster when
1458 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001459 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001460 if (packet_has_ietf_packet_header) {
1461 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001462 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001463 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001464 rv = ProcessDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001465 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001466 }
1467 } else {
1468 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1469 if (packet_has_ietf_packet_header) {
1470 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1471 packet.length());
1472 } else {
1473 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1474 packet.length());
1475 }
1476 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001477 << "than kMaxIncomingPacketSize. packet size:"
1478 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001479 }
1480 return rv;
1481}
1482
1483bool QuicFramer::ProcessVersionNegotiationPacket(
1484 QuicDataReader* reader,
1485 const QuicPacketHeader& header) {
1486 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1487
QUICHE team2252b702019-05-14 23:55:14 -04001488 QuicVersionNegotiationPacket packet(
1489 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001490 // Try reading at least once to raise error if the packet is invalid.
1491 do {
1492 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001493 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001494 set_detailed_error("Unable to read supported version in negotiation.");
1495 RecordDroppedPacketReason(
1496 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1497 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1498 }
nharper4fd11052019-06-04 14:23:22 -07001499 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1500 if (parsed_version != UnsupportedQuicVersion()) {
1501 packet.versions.push_back(parsed_version);
1502 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001503 } while (!reader->IsDoneReading());
1504
dschinazi5a354c92019-05-09 12:18:53 -07001505 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1506 << ParsedQuicVersionVectorToString(packet.versions);
1507
QUICHE teama6ef0a62019-03-07 20:34:33 -05001508 visitor_->OnVersionNegotiationPacket(packet);
1509 return true;
1510}
1511
dschinazi244f6dc2019-05-06 15:45:16 -07001512bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1513 const QuicPacketHeader& header) {
1514 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1515
dschinazi278efae2020-01-28 17:03:09 -08001516 if (version_.HasRetryIntegrityTag()) {
1517 DCHECK(version_.HasLengthPrefixedConnectionIds()) << version_;
1518 const size_t bytes_remaining = reader->BytesRemaining();
1519 if (bytes_remaining <= kRetryIntegrityTagLength) {
1520 set_detailed_error("Retry packet too short to parse integrity tag.");
1521 return false;
1522 }
1523 const size_t retry_token_length =
1524 bytes_remaining - kRetryIntegrityTagLength;
1525 DCHECK_GT(retry_token_length, 0u);
1526 quiche::QuicheStringPiece retry_token;
1527 if (!reader->ReadStringPiece(&retry_token, retry_token_length)) {
1528 set_detailed_error("Failed to read retry token.");
1529 return false;
1530 }
1531 quiche::QuicheStringPiece retry_without_tag =
1532 reader->PreviouslyReadPayload();
1533 quiche::QuicheStringPiece integrity_tag = reader->ReadRemainingPayload();
1534 DCHECK_EQ(integrity_tag.length(), kRetryIntegrityTagLength);
1535 visitor_->OnRetryPacket(EmptyQuicConnectionId(),
1536 header.source_connection_id, retry_token,
1537 integrity_tag, retry_without_tag);
1538 return true;
1539 }
1540
dschinazi244f6dc2019-05-06 15:45:16 -07001541 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001542 if (version_.HasLengthPrefixedConnectionIds()) {
1543 // Parse Original Destination Connection ID.
1544 if (!reader->ReadLengthPrefixedConnectionId(
1545 &original_destination_connection_id)) {
1546 set_detailed_error("Unable to read Original Destination ConnectionId.");
1547 return false;
1548 }
1549 } else {
1550 // Parse Original Destination Connection ID Length.
1551 uint8_t odcil = header.type_byte & 0xf;
1552 if (odcil != 0) {
1553 odcil += kConnectionIdLengthAdjustment;
1554 }
1555
1556 // Parse Original Destination Connection ID.
1557 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1558 set_detailed_error("Unable to read Original Destination ConnectionId.");
1559 return false;
1560 }
dschinazi244f6dc2019-05-06 15:45:16 -07001561 }
1562
dschinazib953d022019-08-01 18:05:58 -07001563 if (!QuicUtils::IsConnectionIdValidForVersion(
1564 original_destination_connection_id, transport_version())) {
1565 set_detailed_error(
1566 "Received Original Destination ConnectionId with invalid length.");
1567 return false;
1568 }
1569
dmcardlecf0bfcf2019-12-13 08:08:21 -08001570 quiche::QuicheStringPiece retry_token = reader->ReadRemainingPayload();
dschinazi244f6dc2019-05-06 15:45:16 -07001571 visitor_->OnRetryPacket(original_destination_connection_id,
dschinazi278efae2020-01-28 17:03:09 -08001572 header.source_connection_id, retry_token,
1573 /*retry_integrity_tag=*/quiche::QuicheStringPiece(),
1574 /*retry_without_tag=*/quiche::QuicheStringPiece());
dschinazi244f6dc2019-05-06 15:45:16 -07001575 return true;
1576}
1577
QUICHE teama6ef0a62019-03-07 20:34:33 -05001578// Seeks the current packet to check for a coalesced packet at the end.
1579// If the IETF length field only spans part of the outer packet,
1580// then there is a coalesced packet after this one.
1581void QuicFramer::MaybeProcessCoalescedPacket(
1582 const QuicDataReader& encrypted_reader,
1583 uint64_t remaining_bytes_length,
1584 const QuicPacketHeader& header) {
1585 if (header.remaining_packet_length >= remaining_bytes_length) {
1586 // There is no coalesced packet.
1587 return;
1588 }
1589
dmcardlecf0bfcf2019-12-13 08:08:21 -08001590 quiche::QuicheStringPiece remaining_data =
1591 encrypted_reader.PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001592 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1593
1594 const char* coalesced_data =
1595 remaining_data.data() + header.remaining_packet_length;
1596 uint64_t coalesced_data_length =
1597 remaining_bytes_length - header.remaining_packet_length;
1598 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1599
1600 QuicPacketHeader coalesced_header;
1601 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
fayangd1160ff2020-02-26 11:57:09 -08001602 // Some implementations pad their INITIAL packets by sending random invalid
1603 // data after the INITIAL, and that is allowed by the specification. If we
1604 // fail to parse a subsequent coalesced packet, simply ignore it.
1605 QUIC_DLOG(INFO) << ENDPOINT
1606 << "Failed to parse received coalesced header of length "
1607 << coalesced_data_length
1608 << " with error: " << detailed_error_ << ": "
1609 << quiche::QuicheTextUtils::HexEncode(coalesced_data,
1610 coalesced_data_length)
1611 << " previous header was " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001612 return;
1613 }
1614
fayang2e445862020-04-06 08:39:22 -07001615 if (coalesced_header.destination_connection_id !=
1616 header.destination_connection_id) {
1617 // Drop coalesced packets with mismatched connection IDs.
1618 QUIC_DLOG(INFO) << ENDPOINT << "Received mismatched coalesced header "
fayangd1160ff2020-02-26 11:57:09 -08001619 << coalesced_header << " previous header was " << header;
fayang2e445862020-04-06 08:39:22 -07001620 QUIC_CODE_COUNT(
1621 quic_received_coalesced_packets_with_mismatched_connection_id);
1622 return;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001623 }
1624
1625 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1626 /*owns_buffer=*/false);
1627 visitor_->OnCoalescedPacket(coalesced_packet);
1628}
1629
1630bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1631 QuicPacketHeader* header) {
1632 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1633 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1634 (header->long_packet_type != INITIAL &&
1635 header->long_packet_type != HANDSHAKE &&
1636 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1637 return true;
1638 }
1639 header->length_length = encrypted_reader->PeekVarInt62Length();
1640 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1641 set_detailed_error("Unable to read long header payload length.");
1642 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1643 }
1644 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1645 if (header->remaining_packet_length > remaining_bytes_length) {
1646 set_detailed_error("Long header payload length longer than packet.");
1647 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1648 }
1649
1650 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1651 *header);
1652
1653 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1654 set_detailed_error("Length TruncateRemaining failed.");
1655 QUIC_BUG << "Length TruncateRemaining failed.";
1656 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1657 }
1658 return true;
1659}
1660
1661bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1662 QuicPacketHeader* header,
1663 const QuicEncryptedPacket& packet,
1664 char* decrypted_buffer,
1665 size_t buffer_length) {
1666 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1667 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001668 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1669 header->remaining_packet_length = 0;
1670 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1671 perspective_ == Perspective::IS_CLIENT) {
1672 // Peek possible stateless reset token. Will only be used on decryption
1673 // failure.
dmcardlecf0bfcf2019-12-13 08:08:21 -08001674 quiche::QuicheStringPiece remaining =
1675 encrypted_reader->PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001676 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1677 header->has_possible_stateless_reset_token = true;
1678 memcpy(&header->possible_stateless_reset_token,
1679 &remaining.data()[remaining.length() -
1680 sizeof(header->possible_stateless_reset_token)],
1681 sizeof(header->possible_stateless_reset_token));
1682 }
1683 }
1684
QUICHE teama6ef0a62019-03-07 20:34:33 -05001685 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1686 return false;
1687 }
1688
dmcardlecf0bfcf2019-12-13 08:08:21 -08001689 quiche::QuicheStringPiece associated_data;
nharper55fa6132019-05-07 19:37:21 -07001690 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001691 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1692 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001693 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1694 header->long_packet_type == INITIAL ||
1695 header->long_packet_type == HANDSHAKE ||
1696 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001697 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001698 QuicPacketNumber base_packet_number;
1699 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001700 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1701 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1702 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1703 }
1704 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001705 } else {
1706 base_packet_number = largest_packet_number_;
1707 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001708 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001709 bool hp_removal_failed = false;
1710 if (version_.HasHeaderProtection()) {
1711 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1712 &full_packet_number, &ad_storage)) {
1713 hp_removal_failed = true;
1714 }
dmcardlecf0bfcf2019-12-13 08:08:21 -08001715 associated_data =
1716 quiche::QuicheStringPiece(ad_storage.data(), ad_storage.size());
nharper55fa6132019-05-07 19:37:21 -07001717 } else if (!ProcessAndCalculatePacketNumber(
1718 encrypted_reader, header->packet_number_length,
1719 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001720 set_detailed_error("Unable to read packet number.");
1721 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1722 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1723 }
1724
nharper55fa6132019-05-07 19:37:21 -07001725 if (hp_removal_failed ||
dschinazi40f0b3d2020-02-19 17:54:05 -08001726 !IsValidFullPacketNumber(full_packet_number, version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001727 if (IsIetfStatelessResetPacket(*header)) {
1728 // This is a stateless reset packet.
1729 QuicIetfStatelessResetPacket packet(
1730 *header, header->possible_stateless_reset_token);
1731 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1732 return true;
1733 }
nharper55fa6132019-05-07 19:37:21 -07001734 if (hp_removal_failed) {
wub13d75452019-11-05 07:24:56 -08001735 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1736 const bool has_decryption_key = decrypter_[decryption_level] != nullptr;
1737 visitor_->OnUndecryptablePacket(
1738 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1739 decryption_level, has_decryption_key);
dschinazi163bda22020-04-01 13:34:43 -07001740 set_detailed_error(quiche::QuicheStrCat(
1741 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
1742 " header protection", has_decryption_key ? "" : " (missing key)",
1743 "."));
nharper55fa6132019-05-07 19:37:21 -07001744 return RaiseError(QUIC_DECRYPTION_FAILURE);
1745 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001746 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1747 set_detailed_error("packet numbers cannot be 0.");
1748 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1749 }
1750 header->packet_number = QuicPacketNumber(full_packet_number);
1751 }
1752
1753 // A nonce should only present in SHLO from the server to the client when
1754 // using QUIC crypto.
1755 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1756 header->long_packet_type == ZERO_RTT_PROTECTED &&
1757 perspective_ == Perspective::IS_CLIENT &&
1758 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1759 if (!encrypted_reader->ReadBytes(
1760 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1761 last_nonce_.size())) {
1762 set_detailed_error("Unable to read nonce.");
1763 RecordDroppedPacketReason(
1764 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1765 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1766 }
1767
1768 header->nonce = &last_nonce_;
1769 } else {
1770 header->nonce = nullptr;
1771 }
1772
1773 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1774 set_detailed_error(
1775 "Visitor asked to stop processing of unauthenticated header.");
1776 return false;
1777 }
1778
dmcardlecf0bfcf2019-12-13 08:08:21 -08001779 quiche::QuicheStringPiece encrypted =
1780 encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001781 if (!version_.HasHeaderProtection()) {
1782 associated_data = GetAssociatedDataFromEncryptedPacket(
1783 version_.transport_version, packet,
1784 GetIncludedDestinationConnectionIdLength(*header),
1785 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1786 header->nonce != nullptr, header->packet_number_length,
1787 header->retry_token_length_length, header->retry_token.length(),
1788 header->length_length);
1789 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001790
1791 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001792 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001793 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001794 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001795 if (IsIetfStatelessResetPacket(*header)) {
1796 // This is a stateless reset packet.
1797 QuicIetfStatelessResetPacket packet(
1798 *header, header->possible_stateless_reset_token);
1799 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1800 return true;
1801 }
wub13d75452019-11-05 07:24:56 -08001802 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1803 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1804 decrypter_[decryption_level] != nullptr;
1805 visitor_->OnUndecryptablePacket(
1806 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1807 has_decryption_key);
dschinazi163bda22020-04-01 13:34:43 -07001808 set_detailed_error(quiche::QuicheStrCat(
1809 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
1810 " payload",
1811 has_decryption_key || !version_.KnowsWhichDecrypterToUse()
1812 ? ""
1813 : " (missing key)",
1814 "."));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001815 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1816 return RaiseError(QUIC_DECRYPTION_FAILURE);
1817 }
1818 QuicDataReader reader(decrypted_buffer, decrypted_length);
1819
1820 // Update the largest packet number after we have decrypted the packet
1821 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001822 if (supports_multiple_packet_number_spaces_) {
1823 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1824 decrypted_level)]
1825 .UpdateMax(header->packet_number);
1826 } else {
1827 largest_packet_number_.UpdateMax(header->packet_number);
1828 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001829
1830 if (!visitor_->OnPacketHeader(*header)) {
1831 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1832 // The visitor suppresses further processing of the packet.
1833 return true;
1834 }
1835
dschinazie8d7fa72019-04-05 14:44:40 -07001836 if (packet.length() > kMaxIncomingPacketSize) {
1837 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001838 return RaiseError(QUIC_PACKET_TOO_LARGE);
1839 }
1840
1841 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001842 if (VersionHasIetfQuicFrames(version_.transport_version)) {
fkastenholza3660102019-08-28 05:19:24 -07001843 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001844 if (!ProcessIetfFrameData(&reader, *header)) {
fkastenholza3660102019-08-28 05:19:24 -07001845 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001846 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1847 DCHECK_NE("", detailed_error_);
1848 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1849 << detailed_error_;
1850 return false;
1851 }
fkastenholza3660102019-08-28 05:19:24 -07001852 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001853 } else {
1854 if (!ProcessFrameData(&reader, *header)) {
1855 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1856 DCHECK_NE("", detailed_error_);
1857 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1858 << detailed_error_;
1859 return false;
1860 }
1861 }
1862
1863 visitor_->OnPacketComplete();
1864 return true;
1865}
1866
1867bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1868 QuicPacketHeader* header,
1869 const QuicEncryptedPacket& packet,
1870 char* decrypted_buffer,
1871 size_t buffer_length) {
1872 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1873 DCHECK_NE("", detailed_error_);
1874 QUIC_DVLOG(1)
1875 << ENDPOINT
1876 << "Unable to process packet header. Stopping parsing. Error: "
1877 << detailed_error_;
1878 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1879 return false;
1880 }
1881
dmcardlecf0bfcf2019-12-13 08:08:21 -08001882 quiche::QuicheStringPiece encrypted =
1883 encrypted_reader->ReadRemainingPayload();
1884 quiche::QuicheStringPiece associated_data =
1885 GetAssociatedDataFromEncryptedPacket(
1886 version_.transport_version, packet,
1887 GetIncludedDestinationConnectionIdLength(*header),
1888 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1889 header->nonce != nullptr, header->packet_number_length,
1890 header->retry_token_length_length, header->retry_token.length(),
1891 header->length_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001892
1893 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001894 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001895 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001896 buffer_length, &decrypted_length, &decrypted_level)) {
wub13d75452019-11-05 07:24:56 -08001897 const EncryptionLevel decryption_level = decrypter_level_;
1898 // This version uses trial decryption so we always report to our visitor
1899 // that we are not certain we have the correct decryption key.
1900 const bool has_decryption_key = false;
1901 visitor_->OnUndecryptablePacket(
1902 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1903 has_decryption_key);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001904 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
dschinazi163bda22020-04-01 13:34:43 -07001905 set_detailed_error(quiche::QuicheStrCat(
1906 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
1907 " payload."));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001908 return RaiseError(QUIC_DECRYPTION_FAILURE);
1909 }
1910
1911 QuicDataReader reader(decrypted_buffer, decrypted_length);
1912
1913 // Update the largest packet number after we have decrypted the packet
1914 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001915 if (supports_multiple_packet_number_spaces_) {
1916 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1917 decrypted_level)]
1918 .UpdateMax(header->packet_number);
1919 } else {
1920 largest_packet_number_.UpdateMax(header->packet_number);
1921 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001922
1923 if (!visitor_->OnPacketHeader(*header)) {
1924 // The visitor suppresses further processing of the packet.
1925 return true;
1926 }
1927
dschinazie8d7fa72019-04-05 14:44:40 -07001928 if (packet.length() > kMaxIncomingPacketSize) {
1929 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001930 return RaiseError(QUIC_PACKET_TOO_LARGE);
1931 }
1932
1933 // Handle the payload.
1934 if (!ProcessFrameData(&reader, *header)) {
1935 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1936 DCHECK_NE("", detailed_error_);
1937 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1938 << detailed_error_;
1939 return false;
1940 }
1941
1942 visitor_->OnPacketComplete();
1943 return true;
1944}
1945
1946bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1947 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001948 QuicPublicResetPacket packet(
1949 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001950
1951 std::unique_ptr<CryptoHandshakeMessage> reset(
1952 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
wub07a2b072019-10-24 11:23:20 -07001953 if (!reset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001954 set_detailed_error("Unable to read reset message.");
1955 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1956 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1957 }
1958 if (reset->tag() != kPRST) {
1959 set_detailed_error("Incorrect message tag.");
1960 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1961 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1962 }
1963
1964 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
1965 set_detailed_error("Unable to read nonce proof.");
1966 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1967 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1968 }
1969 // TODO(satyamshekhar): validate nonce to protect against DoS.
1970
dmcardlecf0bfcf2019-12-13 08:08:21 -08001971 quiche::QuicheStringPiece address;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001972 if (reset->GetStringPiece(kCADR, &address)) {
1973 QuicSocketAddressCoder address_coder;
1974 if (address_coder.Decode(address.data(), address.length())) {
1975 packet.client_address =
1976 QuicSocketAddress(address_coder.ip(), address_coder.port());
1977 }
1978 }
1979
dmcardlecf0bfcf2019-12-13 08:08:21 -08001980 quiche::QuicheStringPiece endpoint_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001981 if (perspective_ == Perspective::IS_CLIENT &&
1982 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07001983 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001984 packet.endpoint_id += '\0';
1985 }
1986
1987 visitor_->OnPublicResetPacket(packet);
1988 return true;
1989}
1990
1991bool QuicFramer::IsIetfStatelessResetPacket(
1992 const QuicPacketHeader& header) const {
1993 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
1994 perspective_ != Perspective::IS_CLIENT)
1995 << "has_possible_stateless_reset_token can only be true at client side.";
1996 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
1997 header.has_possible_stateless_reset_token &&
1998 visitor_->IsValidStatelessResetToken(
1999 header.possible_stateless_reset_token);
2000}
2001
2002bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2003 return encrypter_[level] != nullptr;
2004}
2005
2006bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2007 QuicDataWriter* writer,
2008 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002009 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002010 return AppendIetfPacketHeader(header, writer, length_field_offset);
2011 }
2012 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2013 uint8_t public_flags = 0;
2014 if (header.reset_flag) {
2015 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2016 }
2017 if (header.version_flag) {
2018 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2019 }
2020
2021 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2022 << kPublicHeaderSequenceNumberShift;
2023
2024 if (header.nonce != nullptr) {
2025 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2026 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2027 }
QUICHE team2252b702019-05-14 23:55:14 -04002028
dschinazi7b9278c2019-05-20 07:36:21 -07002029 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002030 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002031 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002032 GetServerConnectionIdIncludedAsSender(header, perspective_);
2033 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002034 GetClientConnectionIdIncludedAsSender(header, perspective_))
2035 << ENDPOINT << ParsedQuicVersionToString(version_)
2036 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002037
dschinazi7b9278c2019-05-20 07:36:21 -07002038 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002039 case CONNECTION_ID_ABSENT:
2040 if (!writer->WriteUInt8(public_flags |
2041 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2042 return false;
2043 }
2044 break;
2045 case CONNECTION_ID_PRESENT:
2046 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002047 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002048 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002049 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002050 << QuicVersionToString(transport_version());
2051
2052 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2053 if (perspective_ == Perspective::IS_CLIENT) {
2054 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2055 }
2056 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002057 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002058 return false;
2059 }
2060 break;
2061 }
dschinazi7b9278c2019-05-20 07:36:21 -07002062 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002063
2064 if (header.version_flag) {
2065 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2066 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002067 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002068 return false;
2069 }
2070
2071 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2072 << QuicVersionLabelToString(version_label) << "'";
2073 }
2074
2075 if (header.nonce != nullptr &&
2076 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2077 return false;
2078 }
2079
2080 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2081 writer)) {
2082 return false;
2083 }
2084
2085 return true;
2086}
2087
2088bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2089 QuicDataWriter* writer) {
2090 uint8_t type = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002091 if (header.version_flag) {
2092 type = static_cast<uint8_t>(
fayang36825da2019-08-21 14:01:27 -07002093 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2094 LongHeaderTypeToOnWireValue(header.long_packet_type) |
2095 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002096 } else {
fayang36825da2019-08-21 14:01:27 -07002097 type = static_cast<uint8_t>(
2098 FLAGS_FIXED_BIT |
2099 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002100 }
2101 return writer->WriteUInt8(type);
2102}
2103
2104bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2105 QuicDataWriter* writer,
2106 size_t* length_field_offset) {
2107 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002108 QuicConnectionId server_connection_id =
2109 GetServerConnectionIdAsSender(header, perspective_);
2110 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2111 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002112 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002113 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002114 << QuicVersionToString(transport_version());
2115 if (!AppendIetfHeaderTypeByte(header, writer)) {
2116 return false;
2117 }
2118
2119 if (header.version_flag) {
dschinaziecad9642019-10-01 10:44:17 -07002120 DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type)
2121 << "QuicFramer::AppendIetfPacketHeader does not support sending "
2122 "version negotiation packets, use "
2123 "QuicFramer::BuildVersionNegotiationPacket instead "
2124 << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002125 // Append version for long header.
2126 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002127 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002128 return false;
2129 }
2130 }
2131
2132 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002133 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002134 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002135 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2136 ? header.destination_connection_id
2137 : EmptyQuicConnectionId(),
2138 header.source_connection_id_included != CONNECTION_ID_ABSENT
2139 ? header.source_connection_id
2140 : EmptyQuicConnectionId(),
2141 writer)) {
2142 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002143 }
dschinazi1f485a12019-05-13 11:57:01 -07002144
dschinazi7b9278c2019-05-20 07:36:21 -07002145 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002146 if (version_.SupportsClientConnectionIds()) {
2147 last_serialized_client_connection_id_ =
2148 GetClientConnectionIdAsSender(header, perspective_);
2149 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002150
dschinaziecad9642019-10-01 10:44:17 -07002151 // TODO(b/141924462) Remove this QUIC_BUG once we do support sending RETRY.
2152 QUIC_BUG_IF(header.version_flag && header.long_packet_type == RETRY)
2153 << "Sending IETF RETRY packets is not currently supported " << header;
2154
QUICHE teama6ef0a62019-03-07 20:34:33 -05002155 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2156 header.version_flag) {
2157 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002158 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2159 header.retry_token_length_length)
2160 << ENDPOINT << ParsedQuicVersionToString(version_)
2161 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002162 // Write retry token length.
2163 if (!writer->WriteVarInt62(header.retry_token.length(),
2164 header.retry_token_length_length)) {
2165 return false;
2166 }
2167 // Write retry token.
2168 if (!header.retry_token.empty() &&
2169 !writer->WriteStringPiece(header.retry_token)) {
2170 return false;
2171 }
2172 }
2173 if (length_field_offset != nullptr) {
2174 *length_field_offset = writer->length();
2175 }
2176 // Add fake length to reserve two bytes to add length in later.
2177 writer->WriteVarInt62(256);
2178 } else if (length_field_offset != nullptr) {
2179 *length_field_offset = 0;
2180 }
2181
2182 // Append packet number.
2183 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2184 writer)) {
2185 return false;
2186 }
nharper55fa6132019-05-07 19:37:21 -07002187 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002188
2189 if (!header.version_flag) {
2190 return true;
2191 }
2192
2193 if (header.nonce != nullptr) {
2194 DCHECK(header.version_flag);
2195 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2196 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2197 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2198 return false;
2199 }
2200 }
2201
2202 return true;
2203}
2204
2205const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2206 uint32_t time_delta_us) {
2207 // The new time_delta might have wrapped to the next epoch, or it
2208 // might have reverse wrapped to the previous epoch, or it might
2209 // remain in the same epoch. Select the time closest to the previous
2210 // time.
2211 //
2212 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2213 // microseconds.
2214 const uint64_t epoch_delta = UINT64_C(1) << 32;
2215 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2216 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2217 uint64_t prev_epoch = epoch - epoch_delta;
2218 uint64_t next_epoch = epoch + epoch_delta;
2219
2220 uint64_t time = ClosestTo(
2221 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2222 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2223 next_epoch + time_delta_us));
2224
2225 return QuicTime::Delta::FromMicroseconds(time);
2226}
2227
2228uint64_t QuicFramer::CalculatePacketNumberFromWire(
2229 QuicPacketNumberLength packet_number_length,
2230 QuicPacketNumber base_packet_number,
2231 uint64_t packet_number) const {
2232 // The new packet number might have wrapped to the next epoch, or
2233 // it might have reverse wrapped to the previous epoch, or it might
2234 // remain in the same epoch. Select the packet number closest to the
2235 // next expected packet number, the previous packet number plus 1.
2236
2237 // epoch_delta is the delta between epochs the packet number was serialized
2238 // with, so the correct value is likely the same epoch as the last sequence
2239 // number or an adjacent epoch.
2240 if (!base_packet_number.IsInitialized()) {
2241 return packet_number;
2242 }
2243 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2244 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2245 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2246 uint64_t prev_epoch = epoch - epoch_delta;
2247 uint64_t next_epoch = epoch + epoch_delta;
2248
2249 return ClosestTo(next_packet_number, epoch + packet_number,
2250 ClosestTo(next_packet_number, prev_epoch + packet_number,
2251 next_epoch + packet_number));
2252}
2253
2254bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2255 bool packet_has_ietf_packet_header,
2256 QuicPacketHeader* header) {
2257 if (packet_has_ietf_packet_header) {
2258 return ProcessIetfPacketHeader(reader, header);
2259 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002260 uint8_t public_flags;
2261 if (!reader->ReadBytes(&public_flags, 1)) {
2262 set_detailed_error("Unable to read public flags.");
2263 return false;
2264 }
2265
2266 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2267 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2268
2269 if (validate_flags_ && !header->version_flag &&
2270 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2271 set_detailed_error("Illegal public flags value.");
2272 return false;
2273 }
2274
2275 if (header->reset_flag && header->version_flag) {
2276 set_detailed_error("Got version flag in reset packet");
2277 return false;
2278 }
2279
QUICHE team2252b702019-05-14 23:55:14 -04002280 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2281 QuicConnectionIdIncluded* header_connection_id_included =
2282 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002283 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002284 header_connection_id = &header->source_connection_id;
2285 header_connection_id_included = &header->source_connection_id_included;
2286 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002287 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2288 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002289 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002290 kQuicDefaultConnectionIdLength)) {
2291 set_detailed_error("Unable to read ConnectionId.");
2292 return false;
2293 }
QUICHE team2252b702019-05-14 23:55:14 -04002294 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002295 break;
2296 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002297 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002298 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002299 break;
2300 }
2301
2302 header->packet_number_length = ReadSequenceNumberLength(
2303 public_flags >> kPublicHeaderSequenceNumberShift);
2304
2305 // Read the version only if the packet is from the client.
2306 // version flag from the server means version negotiation packet.
2307 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2308 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002309 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002310 set_detailed_error("Unable to read protocol version.");
2311 return false;
2312 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002313 // If the version from the new packet is the same as the version of this
2314 // framer, then the public flags should be set to something we understand.
2315 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002316 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2317 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2318 set_detailed_error("Illegal public flags value.");
2319 return false;
2320 }
2321 header->version = version;
2322 }
2323
2324 // A nonce should only be present in packets from the server to the client,
2325 // which are neither version negotiation nor public reset packets.
2326 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2327 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2328 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2329 // The nonce flag from a client is ignored and is assumed to be an older
2330 // client indicating an eight-byte connection ID.
2331 perspective_ == Perspective::IS_CLIENT) {
2332 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2333 last_nonce_.size())) {
2334 set_detailed_error("Unable to read nonce.");
2335 return false;
2336 }
2337 header->nonce = &last_nonce_;
2338 } else {
2339 header->nonce = nullptr;
2340 }
2341
2342 return true;
2343}
2344
2345// static
2346QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05002347 QuicPacketNumber packet_number) {
2348 DCHECK(packet_number.IsInitialized());
2349 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2350 return PACKET_1BYTE_PACKET_NUMBER;
2351 } else if (packet_number <
2352 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2353 return PACKET_2BYTE_PACKET_NUMBER;
2354 } else if (packet_number <
2355 QuicPacketNumber(UINT64_C(1)
2356 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2357 return PACKET_4BYTE_PACKET_NUMBER;
2358 } else {
2359 return PACKET_6BYTE_PACKET_NUMBER;
2360 }
2361}
2362
2363// static
2364uint8_t QuicFramer::GetPacketNumberFlags(
2365 QuicPacketNumberLength packet_number_length) {
2366 switch (packet_number_length) {
2367 case PACKET_1BYTE_PACKET_NUMBER:
2368 return PACKET_FLAGS_1BYTE_PACKET;
2369 case PACKET_2BYTE_PACKET_NUMBER:
2370 return PACKET_FLAGS_2BYTE_PACKET;
2371 case PACKET_4BYTE_PACKET_NUMBER:
2372 return PACKET_FLAGS_4BYTE_PACKET;
2373 case PACKET_6BYTE_PACKET_NUMBER:
2374 case PACKET_8BYTE_PACKET_NUMBER:
2375 return PACKET_FLAGS_8BYTE_PACKET;
2376 default:
2377 QUIC_BUG << "Unreachable case statement.";
2378 return PACKET_FLAGS_8BYTE_PACKET;
2379 }
2380}
2381
2382// static
2383QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2384 const QuicAckFrame& frame) {
2385 AckFrameInfo new_ack_info;
2386 if (frame.packets.Empty()) {
2387 return new_ack_info;
2388 }
2389 // The first block is the last interval. It isn't encoded with the gap-length
2390 // encoding, so skip it.
2391 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2392 auto itr = frame.packets.rbegin();
2393 QuicPacketNumber previous_start = itr->min();
wub13d75452019-11-05 07:24:56 -08002394 new_ack_info.max_block_length = itr->Length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002395 ++itr;
2396
2397 // Don't do any more work after getting information for 256 ACK blocks; any
2398 // more can't be encoded anyway.
2399 for (; itr != frame.packets.rend() &&
2400 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2401 previous_start = itr->min(), ++itr) {
2402 const auto& interval = *itr;
2403 const QuicPacketCount total_gap = previous_start - interval.max();
2404 new_ack_info.num_ack_blocks +=
2405 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2406 std::numeric_limits<uint8_t>::max();
wub13d75452019-11-05 07:24:56 -08002407 new_ack_info.max_block_length =
2408 std::max(new_ack_info.max_block_length, interval.Length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002409 }
2410 return new_ack_info;
2411}
2412
2413bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2414 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002415 QuicPacketNumber base_packet_number;
2416 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002417 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2418 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2419 set_detailed_error("Unable to determine packet number space.");
2420 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2421 }
2422 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002423 } else {
2424 base_packet_number = largest_packet_number_;
2425 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002426 uint64_t full_packet_number;
2427 if (!ProcessAndCalculatePacketNumber(
2428 encrypted_reader, header->packet_number_length, base_packet_number,
2429 &full_packet_number)) {
2430 set_detailed_error("Unable to read packet number.");
2431 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2432 }
2433
dschinazi40f0b3d2020-02-19 17:54:05 -08002434 if (!IsValidFullPacketNumber(full_packet_number, version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002435 set_detailed_error("packet numbers cannot be 0.");
2436 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2437 }
2438 header->packet_number = QuicPacketNumber(full_packet_number);
2439
2440 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2441 set_detailed_error(
2442 "Visitor asked to stop processing of unauthenticated header.");
2443 return false;
2444 }
nharper3f283562019-05-02 16:37:12 -07002445 // The function we are in is called because the framer believes that it is
2446 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2447 // type. Usually, the framer makes that decision based on the framer's
2448 // version, but when the framer is used with Perspective::IS_SERVER, then
2449 // before version negotiation is complete (specifically, before
2450 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2451 // the type byte of the packet.
2452 //
2453 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2454 // to use the IETF packet header type. If that's the case and we're in this
2455 // function, then the packet received is invalid: the framer was expecting an
2456 // IETF packet header and didn't get one.
2457 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002458 set_detailed_error("Invalid public header type for expected version.");
2459 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2460 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002461 return true;
2462}
2463
2464bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2465 QuicPacketHeader* header) {
2466 uint8_t type;
2467 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002468 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002469 return false;
2470 }
dschinazi244f6dc2019-05-06 15:45:16 -07002471 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002472 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002473 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002474 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2475 // Version is always present in long headers.
2476 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002477 // In versions that do not support client connection IDs, we mark the
2478 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002479 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002480 (perspective_ == Perspective::IS_SERVER ||
2481 version_.SupportsClientConnectionIds())
2482 ? CONNECTION_ID_PRESENT
2483 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002484 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002485 (perspective_ == Perspective::IS_CLIENT ||
2486 version_.SupportsClientConnectionIds())
2487 ? CONNECTION_ID_PRESENT
2488 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002489 // Read version tag.
2490 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002491 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002492 set_detailed_error("Unable to read protocol version.");
2493 return false;
2494 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002495 if (!version_label) {
2496 // Version label is 0 indicating this is a version negotiation packet.
2497 header->long_packet_type = VERSION_NEGOTIATION;
2498 } else {
2499 header->version = ParseQuicVersionLabel(version_label);
2500 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayang36825da2019-08-21 14:01:27 -07002501 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002502 set_detailed_error("Fixed bit is 0 in long header.");
2503 return false;
2504 }
fayang36825da2019-08-21 14:01:27 -07002505 if (!GetLongHeaderType(type, &header->long_packet_type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002506 set_detailed_error("Illegal long header type value.");
2507 return false;
2508 }
dschinazi244f6dc2019-05-06 15:45:16 -07002509 if (header->long_packet_type == RETRY) {
2510 if (!version().SupportsRetry()) {
2511 set_detailed_error("RETRY not supported in this version.");
2512 return false;
2513 }
2514 if (perspective_ == Perspective::IS_SERVER) {
2515 set_detailed_error("Client-initiated RETRY is invalid.");
2516 return false;
2517 }
nharper55fa6132019-05-07 19:37:21 -07002518 } else if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002519 header->packet_number_length = GetLongHeaderPacketNumberLength(type);
nharper2ceb97c2019-04-19 11:38:59 -07002520 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002521 }
2522 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002523
2524 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2525 << QuicUtils::QuicLongHeaderTypetoString(
2526 header->long_packet_type);
2527 return true;
2528 }
2529
2530 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2531 // Version is not present in short headers.
2532 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002533 // In versions that do not support client connection IDs, the client will not
2534 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002535 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002536 (perspective_ == Perspective::IS_SERVER ||
2537 version_.SupportsClientConnectionIds())
2538 ? CONNECTION_ID_PRESENT
2539 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002540 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayang36825da2019-08-21 14:01:27 -07002541 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002542 set_detailed_error("Fixed bit is 0 in short header.");
2543 return false;
2544 }
dschinazidc770fc2020-01-13 15:42:41 -08002545 if (!version_.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002546 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002547 }
2548 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2549 return true;
2550}
2551
fayang40315542019-05-09 09:19:09 -07002552// static
2553bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2554 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002555 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002556 return false;
2557 }
fayang40315542019-05-09 09:19:09 -07002558 return true;
2559}
2560
2561// static
fayangccbab732019-05-13 10:11:25 -07002562bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2563 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002564 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002565 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002566 bool should_update_expected_server_connection_id_length,
2567 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002568 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002569 uint8_t* source_connection_id_length,
2570 std::string* detailed_error) {
2571 uint8_t connection_id_lengths_byte;
2572 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2573 *detailed_error = "Unable to read ConnectionId length.";
2574 return false;
2575 }
fayang40315542019-05-09 09:19:09 -07002576 uint8_t dcil =
2577 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2578 if (dcil != 0) {
2579 dcil += kConnectionIdLengthAdjustment;
2580 }
fayang40315542019-05-09 09:19:09 -07002581 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2582 if (scil != 0) {
2583 scil += kConnectionIdLengthAdjustment;
2584 }
dschinazi334f0232019-05-29 16:08:53 -07002585 if (should_update_expected_server_connection_id_length) {
2586 uint8_t server_connection_id_length =
2587 perspective == Perspective::IS_SERVER ? dcil : scil;
2588 if (*expected_server_connection_id_length != server_connection_id_length) {
2589 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2590 << static_cast<int>(*expected_server_connection_id_length)
2591 << " -> " << static_cast<int>(server_connection_id_length);
2592 *expected_server_connection_id_length = server_connection_id_length;
2593 }
2594 }
dschinazi8ff74822019-05-28 16:37:20 -07002595 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002596 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002597 scil != *source_connection_id_length) &&
dschinazi97da52b2020-01-13 15:44:43 -08002598 version.IsKnown() && !version.AllowsVariableLengthConnectionIds()) {
fayang40315542019-05-09 09:19:09 -07002599 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2600 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002601 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002602 return false;
2603 }
2604 *destination_connection_id_length = dcil;
2605 *source_connection_id_length = scil;
2606 return true;
2607}
2608
dschinazib953d022019-08-01 18:05:58 -07002609bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2610 if (!QuicUtils::IsConnectionIdValidForVersion(
2611 GetServerConnectionIdAsRecipient(header, perspective_),
2612 transport_version())) {
2613 set_detailed_error("Received server connection ID with invalid length.");
2614 return false;
2615 }
2616
2617 if (version_.SupportsClientConnectionIds() &&
2618 !QuicUtils::IsConnectionIdValidForVersion(
2619 GetClientConnectionIdAsRecipient(header, perspective_),
2620 transport_version())) {
2621 set_detailed_error("Received client connection ID with invalid length.");
2622 return false;
2623 }
2624 return true;
2625}
2626
QUICHE teama6ef0a62019-03-07 20:34:33 -05002627bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2628 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002629 if (version_.HasLengthPrefixedConnectionIds()) {
2630 uint8_t expected_destination_connection_id_length =
2631 perspective_ == Perspective::IS_CLIENT
2632 ? expected_client_connection_id_length_
2633 : expected_server_connection_id_length_;
2634 QuicVersionLabel version_label;
2635 bool has_length_prefix;
2636 std::string detailed_error;
2637 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2638 reader, expected_destination_connection_id_length,
2639 VersionHasIetfInvariantHeader(version_.transport_version),
2640 &header->type_byte, &header->form, &header->version_flag,
2641 &has_length_prefix, &version_label, &header->version,
2642 &header->destination_connection_id, &header->source_connection_id,
2643 &header->long_packet_type, &header->retry_token_length_length,
2644 &header->retry_token, &detailed_error);
2645 if (parse_result != QUIC_NO_ERROR) {
2646 set_detailed_error(detailed_error);
2647 return false;
2648 }
2649 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2650 header->source_connection_id_included =
2651 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2652 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2653 DCHECK(header->source_connection_id.IsEmpty());
2654 if (perspective_ == Perspective::IS_CLIENT) {
2655 header->source_connection_id = last_serialized_server_connection_id_;
2656 } else {
2657 header->source_connection_id = last_serialized_client_connection_id_;
2658 }
2659 }
dschinazib953d022019-08-01 18:05:58 -07002660
2661 if (!ValidateReceivedConnectionIds(*header)) {
2662 return false;
2663 }
2664
dschinazi48ac9192019-07-31 00:07:26 -07002665 if (header->version_flag &&
fayang36825da2019-08-21 14:01:27 -07002666 header->long_packet_type != VERSION_NEGOTIATION &&
dschinazi48ac9192019-07-31 00:07:26 -07002667 !(header->type_byte & FLAGS_FIXED_BIT)) {
2668 set_detailed_error("Fixed bit is 0 in long header.");
2669 return false;
2670 }
fayang36825da2019-08-21 14:01:27 -07002671 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
dschinazi48ac9192019-07-31 00:07:26 -07002672 set_detailed_error("Fixed bit is 0 in short header.");
2673 return false;
2674 }
2675 if (!header->version_flag) {
fayang36825da2019-08-21 14:01:27 -07002676 if (!version_.HasHeaderProtection()) {
2677 header->packet_number_length =
2678 GetShortHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002679 }
2680 return true;
2681 }
2682 if (header->long_packet_type == RETRY) {
2683 if (!version().SupportsRetry()) {
2684 set_detailed_error("RETRY not supported in this version.");
2685 return false;
2686 }
2687 if (perspective_ == Perspective::IS_SERVER) {
2688 set_detailed_error("Client-initiated RETRY is invalid.");
2689 return false;
2690 }
2691 return true;
2692 }
dschinazi97da52b2020-01-13 15:44:43 -08002693 if (header->version.IsKnown() && !header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002694 header->packet_number_length =
2695 GetLongHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002696 }
2697
2698 return true;
2699 }
2700
QUICHE teama6ef0a62019-03-07 20:34:33 -05002701 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2702 return false;
2703 }
2704
2705 uint8_t destination_connection_id_length =
2706 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002707 ? (perspective_ == Perspective::IS_SERVER
2708 ? expected_server_connection_id_length_
2709 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002710 : 0;
2711 uint8_t source_connection_id_length =
2712 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002713 ? (perspective_ == Perspective::IS_CLIENT
2714 ? expected_server_connection_id_length_
2715 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002716 : 0;
2717 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002718 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002719 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002720 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002721 &expected_server_connection_id_length_,
2722 &destination_connection_id_length, &source_connection_id_length,
2723 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002724 return false;
2725 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002726 }
2727
2728 // Read connection ID.
2729 if (!reader->ReadConnectionId(&header->destination_connection_id,
2730 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002731 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002732 return false;
2733 }
2734
2735 if (!reader->ReadConnectionId(&header->source_connection_id,
2736 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002737 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002738 return false;
2739 }
2740
dschinazi5e1a7b22019-07-31 12:23:21 -07002741 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2742 if (!header->source_connection_id.IsEmpty()) {
2743 DCHECK(!version_.SupportsClientConnectionIds());
2744 set_detailed_error("Client connection ID not supported in this version.");
2745 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002746 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002747 if (perspective_ == Perspective::IS_CLIENT) {
2748 header->source_connection_id = last_serialized_server_connection_id_;
2749 } else {
2750 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002751 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002752 }
2753
dschinazib953d022019-08-01 18:05:58 -07002754 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002755}
2756
2757bool QuicFramer::ProcessAndCalculatePacketNumber(
2758 QuicDataReader* reader,
2759 QuicPacketNumberLength packet_number_length,
2760 QuicPacketNumber base_packet_number,
2761 uint64_t* packet_number) {
2762 uint64_t wire_packet_number;
2763 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2764 return false;
2765 }
2766
2767 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2768 // in case the first guess is incorrect.
2769 *packet_number = CalculatePacketNumberFromWire(
2770 packet_number_length, base_packet_number, wire_packet_number);
2771 return true;
2772}
2773
2774bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2775 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002776 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2777 << "IETF QUIC Framing negotiated but attempting to process frames as "
2778 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002779 if (reader->IsDoneReading()) {
2780 set_detailed_error("Packet has no frames.");
2781 return RaiseError(QUIC_MISSING_PAYLOAD);
2782 }
dschinazi118934b2019-06-13 18:09:08 -07002783 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002784 while (!reader->IsDoneReading()) {
2785 uint8_t frame_type;
2786 if (!reader->ReadBytes(&frame_type, 1)) {
2787 set_detailed_error("Unable to read frame type.");
2788 return RaiseError(QUIC_INVALID_FRAME_DATA);
2789 }
fayang36825da2019-08-21 14:01:27 -07002790 const uint8_t special_mask = transport_version() <= QUIC_VERSION_43
QUICHE teama6ef0a62019-03-07 20:34:33 -05002791 ? kQuicFrameTypeBrokenMask
2792 : kQuicFrameTypeSpecialMask;
2793 if (frame_type & special_mask) {
2794 // Stream Frame
2795 if (frame_type & kQuicFrameTypeStreamMask) {
2796 QuicStreamFrame frame;
2797 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2798 return RaiseError(QUIC_INVALID_STREAM_DATA);
2799 }
dschinazi118934b2019-06-13 18:09:08 -07002800 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002801 if (!visitor_->OnStreamFrame(frame)) {
2802 QUIC_DVLOG(1) << ENDPOINT
2803 << "Visitor asked to stop further processing.";
2804 // Returning true since there was no parsing error.
2805 return true;
2806 }
2807 continue;
2808 }
2809
2810 // Ack Frame
2811 if (frame_type & kQuicFrameTypeAckMask) {
2812 if (!ProcessAckFrame(reader, frame_type)) {
2813 return RaiseError(QUIC_INVALID_ACK_DATA);
2814 }
dschinazi118934b2019-06-13 18:09:08 -07002815 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002816 continue;
2817 }
2818
2819 // This was a special frame type that did not match any
2820 // of the known ones. Error.
2821 set_detailed_error("Illegal frame type.");
2822 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2823 << static_cast<int>(frame_type);
2824 return RaiseError(QUIC_INVALID_FRAME_DATA);
2825 }
2826
2827 switch (frame_type) {
2828 case PADDING_FRAME: {
2829 QuicPaddingFrame frame;
2830 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002831 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002832 if (!visitor_->OnPaddingFrame(frame)) {
2833 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2834 // Returning true since there was no parsing error.
2835 return true;
2836 }
2837 continue;
2838 }
2839
2840 case RST_STREAM_FRAME: {
2841 QuicRstStreamFrame frame;
2842 if (!ProcessRstStreamFrame(reader, &frame)) {
2843 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2844 }
dschinazi118934b2019-06-13 18:09:08 -07002845 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002846 if (!visitor_->OnRstStreamFrame(frame)) {
2847 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2848 // Returning true since there was no parsing error.
2849 return true;
2850 }
2851 continue;
2852 }
2853
2854 case CONNECTION_CLOSE_FRAME: {
2855 QuicConnectionCloseFrame frame;
2856 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2857 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2858 }
2859
dschinazi118934b2019-06-13 18:09:08 -07002860 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2861 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002862 if (!visitor_->OnConnectionCloseFrame(frame)) {
2863 QUIC_DVLOG(1) << ENDPOINT
2864 << "Visitor asked to stop further processing.";
2865 // Returning true since there was no parsing error.
2866 return true;
2867 }
2868 continue;
2869 }
2870
2871 case GOAWAY_FRAME: {
2872 QuicGoAwayFrame goaway_frame;
2873 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2874 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2875 }
dschinazi118934b2019-06-13 18:09:08 -07002876 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2877 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002878 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2879 QUIC_DVLOG(1) << ENDPOINT
2880 << "Visitor asked to stop further processing.";
2881 // Returning true since there was no parsing error.
2882 return true;
2883 }
2884 continue;
2885 }
2886
2887 case WINDOW_UPDATE_FRAME: {
2888 QuicWindowUpdateFrame window_update_frame;
2889 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2890 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2891 }
dschinazi118934b2019-06-13 18:09:08 -07002892 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2893 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002894 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2895 QUIC_DVLOG(1) << ENDPOINT
2896 << "Visitor asked to stop further processing.";
2897 // Returning true since there was no parsing error.
2898 return true;
2899 }
2900 continue;
2901 }
2902
2903 case BLOCKED_FRAME: {
2904 QuicBlockedFrame blocked_frame;
2905 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2906 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2907 }
dschinazi118934b2019-06-13 18:09:08 -07002908 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2909 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002910 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2911 QUIC_DVLOG(1) << ENDPOINT
2912 << "Visitor asked to stop further processing.";
2913 // Returning true since there was no parsing error.
2914 return true;
2915 }
2916 continue;
2917 }
2918
2919 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002920 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayang36825da2019-08-21 14:01:27 -07002921 version_.transport_version > QUIC_VERSION_43) {
ianswett97b690b2019-05-02 15:12:43 -07002922 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2923 set_detailed_error("STOP WAITING not supported in version 44+.");
2924 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2925 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002926 QuicStopWaitingFrame stop_waiting_frame;
2927 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2928 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2929 }
dschinazi118934b2019-06-13 18:09:08 -07002930 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2931 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002932 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2933 QUIC_DVLOG(1) << ENDPOINT
2934 << "Visitor asked to stop further processing.";
2935 // Returning true since there was no parsing error.
2936 return true;
2937 }
2938 continue;
2939 }
2940 case PING_FRAME: {
2941 // Ping has no payload.
2942 QuicPingFrame ping_frame;
2943 if (!visitor_->OnPingFrame(ping_frame)) {
2944 QUIC_DVLOG(1) << ENDPOINT
2945 << "Visitor asked to stop further processing.";
2946 // Returning true since there was no parsing error.
2947 return true;
2948 }
dschinazi118934b2019-06-13 18:09:08 -07002949 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002950 continue;
2951 }
2952 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2953 QUIC_FALLTHROUGH_INTENDED;
2954 case IETF_EXTENSION_MESSAGE: {
2955 QuicMessageFrame message_frame;
2956 if (!ProcessMessageFrame(reader,
2957 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2958 &message_frame)) {
2959 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2960 }
dschinazi118934b2019-06-13 18:09:08 -07002961 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
2962 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002963 if (!visitor_->OnMessageFrame(message_frame)) {
2964 QUIC_DVLOG(1) << ENDPOINT
2965 << "Visitor asked to stop further processing.";
2966 // Returning true since there was no parsing error.
2967 return true;
2968 }
2969 break;
2970 }
2971 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07002972 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002973 set_detailed_error("Illegal frame type.");
2974 return RaiseError(QUIC_INVALID_FRAME_DATA);
2975 }
2976 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08002977 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002978 return RaiseError(QUIC_INVALID_FRAME_DATA);
2979 }
dschinazi118934b2019-06-13 18:09:08 -07002980 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002981 if (!visitor_->OnCryptoFrame(frame)) {
2982 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2983 // Returning true since there was no parsing error.
2984 return true;
2985 }
2986 break;
2987 }
2988
2989 default:
2990 set_detailed_error("Illegal frame type.");
2991 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2992 << static_cast<int>(frame_type);
2993 return RaiseError(QUIC_INVALID_FRAME_DATA);
2994 }
2995 }
2996
2997 return true;
2998}
2999
3000bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3001 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07003002 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3003 << "Attempt to process frames as IETF frames but version ("
3004 << version_.transport_version << ") does not support IETF Framing.";
3005
QUICHE teama6ef0a62019-03-07 20:34:33 -05003006 if (reader->IsDoneReading()) {
3007 set_detailed_error("Packet has no frames.");
3008 return RaiseError(QUIC_MISSING_PAYLOAD);
3009 }
dschinazi118934b2019-06-13 18:09:08 -07003010
3011 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003012 while (!reader->IsDoneReading()) {
3013 uint64_t frame_type;
3014 // Will be the number of bytes into which frame_type was encoded.
3015 size_t encoded_bytes = reader->BytesRemaining();
3016 if (!reader->ReadVarInt62(&frame_type)) {
3017 set_detailed_error("Unable to read frame type.");
3018 return RaiseError(QUIC_INVALID_FRAME_DATA);
3019 }
fkastenholza3660102019-08-28 05:19:24 -07003020 current_received_frame_type_ = frame_type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003021
3022 // Is now the number of bytes into which the frame type was encoded.
3023 encoded_bytes -= reader->BytesRemaining();
3024
3025 // Check that the frame type is minimally encoded.
3026 if (encoded_bytes !=
3027 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3028 // The frame type was not minimally encoded.
3029 set_detailed_error("Frame type not minimally encoded.");
3030 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3031 }
3032
3033 if (IS_IETF_STREAM_FRAME(frame_type)) {
3034 QuicStreamFrame frame;
3035 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3036 return RaiseError(QUIC_INVALID_STREAM_DATA);
3037 }
dschinazi118934b2019-06-13 18:09:08 -07003038 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003039 if (!visitor_->OnStreamFrame(frame)) {
3040 QUIC_DVLOG(1) << ENDPOINT
3041 << "Visitor asked to stop further processing.";
3042 // Returning true since there was no parsing error.
3043 return true;
3044 }
3045 } else {
3046 switch (frame_type) {
3047 case IETF_PADDING: {
3048 QuicPaddingFrame frame;
3049 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003050 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3051 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003052 if (!visitor_->OnPaddingFrame(frame)) {
3053 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3054 // Returning true since there was no parsing error.
3055 return true;
3056 }
3057 break;
3058 }
3059 case IETF_RST_STREAM: {
3060 QuicRstStreamFrame frame;
3061 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3062 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3063 }
dschinazi118934b2019-06-13 18:09:08 -07003064 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3065 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003066 if (!visitor_->OnRstStreamFrame(frame)) {
3067 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3068 // Returning true since there was no parsing error.
3069 return true;
3070 }
3071 break;
3072 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003073 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003074 case IETF_CONNECTION_CLOSE: {
3075 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003076 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003077 reader,
3078 (frame_type == IETF_CONNECTION_CLOSE)
3079 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3080 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3081 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003082 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3083 }
dschinazi118934b2019-06-13 18:09:08 -07003084 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3085 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003086 if (!visitor_->OnConnectionCloseFrame(frame)) {
3087 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3088 // Returning true since there was no parsing error.
3089 return true;
3090 }
3091 break;
3092 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003093 case IETF_MAX_DATA: {
3094 QuicWindowUpdateFrame frame;
3095 if (!ProcessMaxDataFrame(reader, &frame)) {
3096 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3097 }
dschinazi118934b2019-06-13 18:09:08 -07003098 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3099 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003100 if (!visitor_->OnWindowUpdateFrame(frame)) {
3101 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3102 // Returning true since there was no parsing error.
3103 return true;
3104 }
3105 break;
3106 }
3107 case IETF_MAX_STREAM_DATA: {
3108 QuicWindowUpdateFrame frame;
3109 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3110 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3111 }
dschinazi118934b2019-06-13 18:09:08 -07003112 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3113 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003114 if (!visitor_->OnWindowUpdateFrame(frame)) {
3115 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3116 // Returning true since there was no parsing error.
3117 return true;
3118 }
3119 break;
3120 }
3121 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3122 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003123 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003124 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003125 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003126 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003127 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003128 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3129 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003130 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003131 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3132 // Returning true since there was no parsing error.
3133 return true;
3134 }
3135 break;
3136 }
3137 case IETF_PING: {
3138 // Ping has no payload.
3139 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003140 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3141 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003142 if (!visitor_->OnPingFrame(ping_frame)) {
3143 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3144 // Returning true since there was no parsing error.
3145 return true;
3146 }
3147 break;
3148 }
ianswett2f077442019-12-12 11:51:24 -08003149 case IETF_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003150 QuicBlockedFrame frame;
renjietangf8a9c8c2020-03-19 16:47:03 -07003151 if (!ProcessDataBlockedFrame(reader, &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003152 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3153 }
dschinazi118934b2019-06-13 18:09:08 -07003154 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3155 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003156 if (!visitor_->OnBlockedFrame(frame)) {
3157 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3158 // Returning true since there was no parsing error.
3159 return true;
3160 }
3161 break;
3162 }
ianswett2f077442019-12-12 11:51:24 -08003163 case IETF_STREAM_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003164 QuicBlockedFrame frame;
renjietangf8a9c8c2020-03-19 16:47:03 -07003165 if (!ProcessStreamDataBlockedFrame(reader, &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003166 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3167 }
dschinazi118934b2019-06-13 18:09:08 -07003168 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3169 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003170 if (!visitor_->OnBlockedFrame(frame)) {
3171 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3172 // Returning true since there was no parsing error.
3173 return true;
3174 }
3175 break;
3176 }
3177 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3178 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003179 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003180 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003181 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003182 }
dschinazi118934b2019-06-13 18:09:08 -07003183 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3184 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003185 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003186 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3187 // Returning true since there was no parsing error.
3188 return true;
3189 }
3190 break;
3191 }
3192 case IETF_NEW_CONNECTION_ID: {
3193 QuicNewConnectionIdFrame frame;
3194 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3195 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3196 }
dschinazi118934b2019-06-13 18:09:08 -07003197 QUIC_DVLOG(2) << ENDPOINT
3198 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003199 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3200 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3201 // Returning true since there was no parsing error.
3202 return true;
3203 }
3204 break;
3205 }
3206 case IETF_RETIRE_CONNECTION_ID: {
3207 QuicRetireConnectionIdFrame frame;
3208 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3209 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3210 }
dschinazi118934b2019-06-13 18:09:08 -07003211 QUIC_DVLOG(2) << ENDPOINT
3212 << "Processing IETF retire connection ID frame "
3213 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003214 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3215 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3216 // Returning true since there was no parsing error.
3217 return true;
3218 }
3219 break;
3220 }
3221 case IETF_NEW_TOKEN: {
3222 QuicNewTokenFrame frame;
3223 if (!ProcessNewTokenFrame(reader, &frame)) {
3224 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3225 }
dschinazi118934b2019-06-13 18:09:08 -07003226 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3227 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003228 if (!visitor_->OnNewTokenFrame(frame)) {
3229 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3230 // Returning true since there was no parsing error.
3231 return true;
3232 }
3233 break;
3234 }
3235 case IETF_STOP_SENDING: {
3236 QuicStopSendingFrame frame;
3237 if (!ProcessStopSendingFrame(reader, &frame)) {
3238 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3239 }
dschinazi118934b2019-06-13 18:09:08 -07003240 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3241 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003242 if (!visitor_->OnStopSendingFrame(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_ACK_ECN:
3250 case IETF_ACK: {
3251 QuicAckFrame frame;
3252 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3253 return RaiseError(QUIC_INVALID_ACK_DATA);
3254 }
dschinazi118934b2019-06-13 18:09:08 -07003255 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003256 break;
3257 }
3258 case IETF_PATH_CHALLENGE: {
3259 QuicPathChallengeFrame frame;
3260 if (!ProcessPathChallengeFrame(reader, &frame)) {
3261 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3262 }
dschinazi118934b2019-06-13 18:09:08 -07003263 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3264 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003265 if (!visitor_->OnPathChallengeFrame(frame)) {
3266 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3267 // Returning true since there was no parsing error.
3268 return true;
3269 }
3270 break;
3271 }
3272 case IETF_PATH_RESPONSE: {
3273 QuicPathResponseFrame frame;
3274 if (!ProcessPathResponseFrame(reader, &frame)) {
3275 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3276 }
dschinazi118934b2019-06-13 18:09:08 -07003277 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3278 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003279 if (!visitor_->OnPathResponseFrame(frame)) {
3280 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3281 // Returning true since there was no parsing error.
3282 return true;
3283 }
3284 break;
3285 }
dschinazicd86dd12019-11-14 10:11:13 -08003286 case IETF_EXTENSION_MESSAGE_NO_LENGTH_V99:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003287 QUIC_FALLTHROUGH_INTENDED;
dschinazicd86dd12019-11-14 10:11:13 -08003288 case IETF_EXTENSION_MESSAGE_V99: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003289 QuicMessageFrame message_frame;
3290 if (!ProcessMessageFrame(
dschinazicd86dd12019-11-14 10:11:13 -08003291 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH_V99,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003292 &message_frame)) {
3293 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3294 }
dschinazi118934b2019-06-13 18:09:08 -07003295 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3296 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003297 if (!visitor_->OnMessageFrame(message_frame)) {
3298 QUIC_DVLOG(1) << ENDPOINT
3299 << "Visitor asked to stop further processing.";
3300 // Returning true since there was no parsing error.
3301 return true;
3302 }
3303 break;
3304 }
3305 case IETF_CRYPTO: {
3306 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08003307 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003308 return RaiseError(QUIC_INVALID_FRAME_DATA);
3309 }
dschinazi118934b2019-06-13 18:09:08 -07003310 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003311 if (!visitor_->OnCryptoFrame(frame)) {
3312 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3313 // Returning true since there was no parsing error.
3314 return true;
3315 }
3316 break;
3317 }
fayang01062942020-01-22 07:23:23 -08003318 case IETF_HANDSHAKE_DONE: {
3319 // HANDSHAKE_DONE has no payload.
3320 QuicHandshakeDoneFrame handshake_done_frame;
3321 if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) {
3322 QUIC_DVLOG(1) << ENDPOINT
3323 << "Visitor asked to stop further processing.";
3324 // Returning true since there was no parsing error.
3325 return true;
3326 }
3327 QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame "
3328 << handshake_done_frame;
3329 break;
3330 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003331
3332 default:
3333 set_detailed_error("Illegal frame type.");
3334 QUIC_DLOG(WARNING)
3335 << ENDPOINT
3336 << "Illegal frame type: " << static_cast<int>(frame_type);
3337 return RaiseError(QUIC_INVALID_FRAME_DATA);
3338 }
3339 }
3340 }
3341 return true;
3342}
3343
3344namespace {
3345// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3346inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3347 return (1u << num_bits) - 1;
3348}
3349
3350// Extract |num_bits| from |flags| offset by |offset|.
3351uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3352 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3353}
3354
3355// Extract the bit at position |offset| from |flags| as a bool.
3356bool ExtractBit(uint8_t flags, uint8_t offset) {
3357 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3358}
3359
3360// Set |num_bits|, offset by |offset| to |val| in |flags|.
3361void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3362 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3363 *flags |= val << offset;
3364}
3365
3366// Set the bit at position |offset| to |val| in |flags|.
3367void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3368 SetBits(flags, val ? 1 : 0, 1, offset);
3369}
3370} // namespace
3371
3372bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3373 uint8_t frame_type,
3374 QuicStreamFrame* frame) {
3375 uint8_t stream_flags = frame_type;
3376
3377 uint8_t stream_id_length = 0;
3378 uint8_t offset_length = 4;
3379 bool has_data_length = true;
3380 stream_flags &= ~kQuicFrameTypeStreamMask;
3381
3382 // Read from right to left: StreamID, Offset, Data Length, Fin.
3383 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3384 stream_flags >>= kQuicStreamIdShift;
3385
3386 offset_length = (stream_flags & kQuicStreamOffsetMask);
3387 // There is no encoding for 1 byte, only 0 and 2 through 8.
3388 if (offset_length > 0) {
3389 offset_length += 1;
3390 }
3391 stream_flags >>= kQuicStreamShift;
3392
3393 has_data_length =
3394 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3395 stream_flags >>= kQuicStreamDataLengthShift;
3396
3397 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3398
3399 uint64_t stream_id;
3400 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3401 set_detailed_error("Unable to read stream_id.");
3402 return false;
3403 }
3404 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3405
3406 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3407 set_detailed_error("Unable to read offset.");
3408 return false;
3409 }
3410
dmcardlecf0bfcf2019-12-13 08:08:21 -08003411 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3412 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003413 if (has_data_length) {
3414 if (!reader->ReadStringPiece16(&data)) {
3415 set_detailed_error("Unable to read frame data.");
3416 return false;
3417 }
3418 } else {
3419 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3420 set_detailed_error("Unable to read frame data.");
3421 return false;
3422 }
3423 }
3424 frame->data_buffer = data.data();
3425 frame->data_length = static_cast<uint16_t>(data.length());
3426
3427 return true;
3428}
3429
3430bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3431 uint8_t frame_type,
3432 QuicStreamFrame* frame) {
3433 // Read stream id from the frame. It's always present.
renjietangd077f8c2020-03-23 17:22:09 -07003434 if (!ReadUint32FromVarint62(reader, IETF_STREAM, &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003435 return false;
3436 }
3437
3438 // If we have a data offset, read it. If not, set to 0.
3439 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3440 if (!reader->ReadVarInt62(&frame->offset)) {
3441 set_detailed_error("Unable to read stream data offset.");
3442 return false;
3443 }
3444 } else {
3445 // no offset in the frame, ensure it's 0 in the Frame.
3446 frame->offset = 0;
3447 }
3448
3449 // If we have a data length, read it. If not, set to 0.
3450 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
dschinazi5c70d482020-04-27 15:58:16 -07003451 uint64_t length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003452 if (!reader->ReadVarInt62(&length)) {
3453 set_detailed_error("Unable to read stream data length.");
3454 return false;
3455 }
dschinazi5c70d482020-04-27 15:58:16 -07003456 if (length > std::numeric_limits<decltype(frame->data_length)>::max()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003457 set_detailed_error("Stream data length is too large.");
3458 return false;
3459 }
3460 frame->data_length = length;
3461 } else {
3462 // no length in the frame, it is the number of bytes remaining in the
3463 // packet.
3464 frame->data_length = reader->BytesRemaining();
3465 }
3466
3467 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3468 frame->fin = true;
3469 } else {
3470 frame->fin = false;
3471 }
3472
dmcardlecf0bfcf2019-12-13 08:08:21 -08003473 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3474 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003475 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3476 set_detailed_error("Unable to read frame data.");
3477 return false;
3478 }
3479 frame->data_buffer = data.data();
dschinazi5c70d482020-04-27 15:58:16 -07003480 DCHECK_EQ(frame->data_length, data.length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003481
3482 return true;
3483}
3484
3485bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
renjietang15dfaa82020-01-03 16:13:38 -08003486 EncryptionLevel encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003487 QuicCryptoFrame* frame) {
renjietang15dfaa82020-01-03 16:13:38 -08003488 frame->level = encryption_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003489 if (!reader->ReadVarInt62(&frame->offset)) {
3490 set_detailed_error("Unable to read crypto data offset.");
3491 return false;
3492 }
3493 uint64_t len;
3494 if (!reader->ReadVarInt62(&len) ||
3495 len > std::numeric_limits<QuicPacketLength>::max()) {
3496 set_detailed_error("Invalid data length.");
3497 return false;
3498 }
3499 frame->data_length = len;
3500
dmcardlecf0bfcf2019-12-13 08:08:21 -08003501 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3502 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003503 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3504 set_detailed_error("Unable to read frame data.");
3505 return false;
3506 }
3507 frame->data_buffer = data.data();
3508 return true;
3509}
3510
3511bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3512 const bool has_ack_blocks =
3513 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3514 uint8_t num_ack_blocks = 0;
3515 uint8_t num_received_packets = 0;
3516
3517 // Determine the two lengths from the frame type: largest acked length,
3518 // ack block length.
3519 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003520 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3521 kActBlockLengthOffset));
3522 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003523 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3524 kLargestAckedOffset));
3525
3526 uint64_t largest_acked;
3527 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3528 set_detailed_error("Unable to read largest acked.");
3529 return false;
3530 }
3531
3532 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3533 // Connection always sends packet starting from kFirstSendingPacketNumber >
3534 // 0, peer has observed an unsent packet.
3535 set_detailed_error("Largest acked is 0.");
3536 return false;
3537 }
3538
3539 uint64_t ack_delay_time_us;
3540 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3541 set_detailed_error("Unable to read ack delay time.");
3542 return false;
3543 }
3544
3545 if (!visitor_->OnAckFrameStart(
3546 QuicPacketNumber(largest_acked),
3547 ack_delay_time_us == kUFloat16MaxValue
3548 ? QuicTime::Delta::Infinite()
3549 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3550 // The visitor suppresses further processing of the packet. Although this is
3551 // not a parsing error, returns false as this is in middle of processing an
3552 // ack frame,
3553 set_detailed_error("Visitor suppresses further processing of ack frame.");
3554 return false;
3555 }
3556
3557 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3558 set_detailed_error("Unable to read num of ack blocks.");
3559 return false;
3560 }
3561
3562 uint64_t first_block_length;
3563 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3564 set_detailed_error("Unable to read first ack block length.");
3565 return false;
3566 }
3567
3568 if (first_block_length == 0) {
3569 set_detailed_error("First block length is zero.");
3570 return false;
3571 }
3572 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3573 if (first_block_length + first_sending_packet_number_.ToUint64() >
3574 largest_acked + 1) {
3575 first_ack_block_underflow = true;
3576 }
3577 if (first_ack_block_underflow) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003578 set_detailed_error(
3579 quiche::QuicheStrCat("Underflow with first ack block length ",
3580 first_block_length, " largest acked is ",
3581 largest_acked, ".")
3582 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003583 return false;
3584 }
3585
3586 uint64_t first_received = largest_acked + 1 - first_block_length;
3587 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3588 QuicPacketNumber(largest_acked + 1))) {
3589 // The visitor suppresses further processing of the packet. Although
3590 // this is not a parsing error, returns false as this is in middle
3591 // of processing an ack frame,
3592 set_detailed_error("Visitor suppresses further processing of ack frame.");
3593 return false;
3594 }
3595
3596 if (num_ack_blocks > 0) {
3597 for (size_t i = 0; i < num_ack_blocks; ++i) {
3598 uint8_t gap = 0;
3599 if (!reader->ReadUInt8(&gap)) {
3600 set_detailed_error("Unable to read gap to next ack block.");
3601 return false;
3602 }
3603 uint64_t current_block_length;
3604 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3605 set_detailed_error("Unable to ack block length.");
3606 return false;
3607 }
3608 bool ack_block_underflow = first_received < gap + current_block_length;
3609 if (first_received < gap + current_block_length +
3610 first_sending_packet_number_.ToUint64()) {
3611 ack_block_underflow = true;
3612 }
3613 if (ack_block_underflow) {
3614 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003615 quiche::QuicheStrCat("Underflow with ack block length ",
3616 current_block_length, ", end of block is ",
3617 first_received - gap, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003618 .c_str());
3619 return false;
3620 }
3621
3622 first_received -= (gap + current_block_length);
3623 if (current_block_length > 0) {
3624 if (!visitor_->OnAckRange(
3625 QuicPacketNumber(first_received),
3626 QuicPacketNumber(first_received) + current_block_length)) {
3627 // The visitor suppresses further processing of the packet. Although
3628 // this is not a parsing error, returns false as this is in middle
3629 // of processing an ack frame,
3630 set_detailed_error(
3631 "Visitor suppresses further processing of ack frame.");
3632 return false;
3633 }
3634 }
3635 }
3636 }
3637
3638 if (!reader->ReadUInt8(&num_received_packets)) {
3639 set_detailed_error("Unable to read num received packets.");
3640 return false;
3641 }
3642
3643 if (!ProcessTimestampsInAckFrame(num_received_packets,
3644 QuicPacketNumber(largest_acked), reader)) {
3645 return false;
3646 }
3647
3648 // Done processing the ACK frame.
fayang533cb1b2020-01-28 08:05:08 -08003649 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(first_received))) {
3650 set_detailed_error(
3651 "Error occurs when visitor finishes processing the ACK frame.");
3652 return false;
3653 }
3654
3655 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003656}
3657
3658bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3659 QuicPacketNumber largest_acked,
3660 QuicDataReader* reader) {
3661 if (num_received_packets == 0) {
3662 return true;
3663 }
3664 uint8_t delta_from_largest_observed;
3665 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3666 set_detailed_error("Unable to read sequence delta in received packets.");
3667 return false;
3668 }
3669
3670 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003671 set_detailed_error(
3672 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3673 delta_from_largest_observed,
3674 ", largest_acked: ", largest_acked.ToUint64())
3675 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003676 return false;
3677 }
3678
3679 // Time delta from the framer creation.
3680 uint32_t time_delta_us;
3681 if (!reader->ReadUInt32(&time_delta_us)) {
3682 set_detailed_error("Unable to read time delta in received packets.");
3683 return false;
3684 }
3685
3686 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3687 if (process_timestamps_) {
3688 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3689
3690 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3691 }
3692
3693 for (uint8_t i = 1; i < num_received_packets; ++i) {
3694 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3695 set_detailed_error("Unable to read sequence delta in received packets.");
3696 return false;
3697 }
3698 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3699 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003700 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3701 delta_from_largest_observed,
3702 ", largest_acked: ", largest_acked.ToUint64())
QUICHE teama6ef0a62019-03-07 20:34:33 -05003703 .c_str());
3704 return false;
3705 }
3706 seq_num = largest_acked - delta_from_largest_observed;
3707
3708 // Time delta from the previous timestamp.
3709 uint64_t incremental_time_delta_us;
3710 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3711 set_detailed_error(
3712 "Unable to read incremental time delta in received packets.");
3713 return false;
3714 }
3715
3716 if (process_timestamps_) {
3717 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3718 incremental_time_delta_us);
3719 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3720 }
3721 }
3722 return true;
3723}
3724
3725bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3726 uint64_t frame_type,
3727 QuicAckFrame* ack_frame) {
3728 uint64_t largest_acked;
3729 if (!reader->ReadVarInt62(&largest_acked)) {
3730 set_detailed_error("Unable to read largest acked.");
3731 return false;
3732 }
3733 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3734 // Connection always sends packet starting from kFirstSendingPacketNumber >
3735 // 0, peer has observed an unsent packet.
3736 set_detailed_error("Largest acked is 0.");
3737 return false;
3738 }
3739 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3740 uint64_t ack_delay_time_in_us;
3741 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3742 set_detailed_error("Unable to read ack delay time.");
3743 return false;
3744 }
3745
fayang3371b092019-12-04 07:08:52 -08003746 if (ack_delay_time_in_us >= (kVarInt62MaxValue >> peer_ack_delay_exponent_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003747 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3748 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003749 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003750 ack_frame->ack_delay_time =
3751 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3752 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003753 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3754 ack_frame->ack_delay_time)) {
3755 // The visitor suppresses further processing of the packet. Although this is
3756 // not a parsing error, returns false as this is in middle of processing an
3757 // ACK frame.
3758 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3759 return false;
3760 }
3761
3762 // Get number of ACK blocks from the packet.
3763 uint64_t ack_block_count;
3764 if (!reader->ReadVarInt62(&ack_block_count)) {
3765 set_detailed_error("Unable to read ack block count.");
3766 return false;
3767 }
3768 // There always is a first ACK block, which is the (number of packets being
3769 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3770 // value is 0, then only largest is acked. If it is 1, then largest-1,
3771 // largest] are acked, etc
3772 uint64_t ack_block_value;
3773 if (!reader->ReadVarInt62(&ack_block_value)) {
3774 set_detailed_error("Unable to read first ack block length.");
3775 return false;
3776 }
3777 // Calculate the packets being acked in the first block.
3778 // +1 because AddRange implementation requires [low,high)
3779 uint64_t block_high = largest_acked + 1;
3780 uint64_t block_low = largest_acked - ack_block_value;
3781
3782 // ack_block_value is the number of packets preceding the
3783 // largest_acked packet which are in the block being acked. Thus,
3784 // its maximum value is largest_acked-1. Test this, reporting an
3785 // error if the value is wrong.
3786 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3787 largest_acked) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003788 set_detailed_error(
3789 quiche::QuicheStrCat("Underflow with first ack block length ",
3790 ack_block_value + 1, " largest acked is ",
3791 largest_acked, ".")
3792 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003793 return false;
3794 }
3795
3796 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3797 QuicPacketNumber(block_high))) {
3798 // The visitor suppresses further processing of the packet. Although
3799 // this is not a parsing error, returns false as this is in middle
3800 // of processing an ACK frame.
3801 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3802 return false;
3803 }
3804
3805 while (ack_block_count != 0) {
3806 uint64_t gap_block_value;
3807 // Get the sizes of the gap and ack blocks,
3808 if (!reader->ReadVarInt62(&gap_block_value)) {
3809 set_detailed_error("Unable to read gap block value.");
3810 return false;
3811 }
3812 // It's an error if the gap is larger than the space from packet
3813 // number 0 to the start of the block that's just been acked, PLUS
3814 // there must be space for at least 1 packet to be acked. For
3815 // example, if block_low is 10 and gap_block_value is 9, it means
3816 // the gap block is 10 packets long, leaving no room for a packet
3817 // to be acked. Thus, gap_block_value+2 can not be larger than
3818 // block_low.
3819 // The test is written this way to detect wrap-arounds.
3820 if ((gap_block_value + 2) > block_low) {
3821 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003822 quiche::QuicheStrCat("Underflow with gap block length ",
3823 gap_block_value + 1,
3824 " previous ack block start is ", block_low, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003825 .c_str());
3826 return false;
3827 }
3828
3829 // Adjust block_high to be the top of the next ack block.
3830 // There is a gap of |gap_block_value| packets between the bottom
3831 // of ack block N and top of block N+1. Note that gap_block_value
3832 // is he size of the gap minus 1 (per the QUIC protocol), and
3833 // block_high is the packet number of the first packet of the gap
3834 // (per the implementation of OnAckRange/AddAckRange, below).
3835 block_high = block_low - 1 - gap_block_value;
3836
3837 if (!reader->ReadVarInt62(&ack_block_value)) {
3838 set_detailed_error("Unable to read ack block value.");
3839 return false;
3840 }
3841 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3842 (block_high - 1)) {
3843 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003844 quiche::QuicheStrCat("Underflow with ack block length ",
3845 ack_block_value + 1, " latest ack block end is ",
3846 block_high - 1, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003847 .c_str());
3848 return false;
3849 }
3850 // Calculate the low end of the new nth ack block. The +1 is
3851 // because the encoded value is the blocksize-1.
3852 block_low = block_high - 1 - ack_block_value;
3853 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3854 QuicPacketNumber(block_high))) {
3855 // The visitor suppresses further processing of the packet. Although
3856 // this is not a parsing error, returns false as this is in middle
3857 // of processing an ACK frame.
3858 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3859 return false;
3860 }
3861
3862 // Another one done.
3863 ack_block_count--;
3864 }
3865
fayang91c23d72020-03-09 12:35:05 -07003866 if (frame_type == IETF_ACK_ECN) {
3867 ack_frame->ecn_counters_populated = true;
3868 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3869 set_detailed_error("Unable to read ack ect_0_count.");
3870 return false;
3871 }
3872 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3873 set_detailed_error("Unable to read ack ect_1_count.");
3874 return false;
3875 }
3876 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3877 set_detailed_error("Unable to read ack ecn_ce_count.");
3878 return false;
3879 }
3880 } else {
3881 ack_frame->ecn_counters_populated = false;
3882 ack_frame->ect_0_count = 0;
3883 ack_frame->ect_1_count = 0;
3884 ack_frame->ecn_ce_count = 0;
3885 }
3886 // TODO(fayang): Report ECN counts to visitor when they are actually used.
fayang533cb1b2020-01-28 08:05:08 -08003887 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(block_low))) {
3888 set_detailed_error(
3889 "Error occurs when visitor finishes processing the ACK frame.");
3890 return false;
3891 }
3892
3893 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003894}
3895
3896bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3897 const QuicPacketHeader& header,
3898 QuicStopWaitingFrame* stop_waiting) {
3899 uint64_t least_unacked_delta;
3900 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3901 &least_unacked_delta)) {
3902 set_detailed_error("Unable to read least unacked delta.");
3903 return false;
3904 }
3905 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3906 set_detailed_error("Invalid unacked delta.");
3907 return false;
3908 }
3909 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3910
3911 return true;
3912}
3913
3914bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3915 QuicRstStreamFrame* frame) {
3916 if (!reader->ReadUInt32(&frame->stream_id)) {
3917 set_detailed_error("Unable to read stream_id.");
3918 return false;
3919 }
3920
3921 if (!reader->ReadUInt64(&frame->byte_offset)) {
3922 set_detailed_error("Unable to read rst stream sent byte offset.");
3923 return false;
3924 }
3925
3926 uint32_t error_code;
3927 if (!reader->ReadUInt32(&error_code)) {
3928 set_detailed_error("Unable to read rst stream error code.");
3929 return false;
3930 }
3931
3932 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3933 // Ignore invalid stream error code if any.
3934 error_code = QUIC_STREAM_LAST_ERROR;
3935 }
3936
3937 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3938
3939 return true;
3940}
3941
3942bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3943 QuicConnectionCloseFrame* frame) {
3944 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003945 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3946
QUICHE teama6ef0a62019-03-07 20:34:33 -05003947 if (!reader->ReadUInt32(&error_code)) {
3948 set_detailed_error("Unable to read connection close error code.");
3949 return false;
3950 }
3951
3952 if (error_code >= QUIC_LAST_ERROR) {
3953 // Ignore invalid QUIC error code if any.
3954 error_code = QUIC_LAST_ERROR;
3955 }
3956
bnc77e77b82020-04-05 10:36:49 -07003957 // For Google QUIC connection closes, |wire_error_code| and |quic_error_code|
3958 // must have the same value.
3959 frame->wire_error_code = error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003960 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003961
dmcardlecf0bfcf2019-12-13 08:08:21 -08003962 quiche::QuicheStringPiece error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003963 if (!reader->ReadStringPiece16(&error_details)) {
3964 set_detailed_error("Unable to read connection close error details.");
3965 return false;
3966 }
vasilvvc48c8712019-03-11 13:38:16 -07003967 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003968
3969 return true;
3970}
3971
3972bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3973 QuicGoAwayFrame* frame) {
3974 uint32_t error_code;
3975 if (!reader->ReadUInt32(&error_code)) {
3976 set_detailed_error("Unable to read go away error code.");
3977 return false;
3978 }
3979
3980 if (error_code >= QUIC_LAST_ERROR) {
3981 // Ignore invalid QUIC error code if any.
3982 error_code = QUIC_LAST_ERROR;
3983 }
3984 frame->error_code = static_cast<QuicErrorCode>(error_code);
3985
3986 uint32_t stream_id;
3987 if (!reader->ReadUInt32(&stream_id)) {
3988 set_detailed_error("Unable to read last good stream id.");
3989 return false;
3990 }
3991 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
3992
dmcardlecf0bfcf2019-12-13 08:08:21 -08003993 quiche::QuicheStringPiece reason_phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003994 if (!reader->ReadStringPiece16(&reason_phrase)) {
3995 set_detailed_error("Unable to read goaway reason.");
3996 return false;
3997 }
vasilvvc48c8712019-03-11 13:38:16 -07003998 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003999
4000 return true;
4001}
4002
4003bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
4004 QuicWindowUpdateFrame* frame) {
4005 if (!reader->ReadUInt32(&frame->stream_id)) {
4006 set_detailed_error("Unable to read stream_id.");
4007 return false;
4008 }
4009
renjietangd088eab2019-11-21 14:54:41 -08004010 if (!reader->ReadUInt64(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004011 set_detailed_error("Unable to read window byte_offset.");
4012 return false;
4013 }
4014
4015 return true;
4016}
4017
4018bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4019 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004020 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4021 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004022
4023 if (!reader->ReadUInt32(&frame->stream_id)) {
4024 set_detailed_error("Unable to read stream_id.");
4025 return false;
4026 }
4027
4028 return true;
4029}
4030
4031void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4032 QuicPaddingFrame* frame) {
4033 // Type byte has been read.
4034 frame->num_padding_bytes = 1;
4035 uint8_t next_byte;
4036 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4037 reader->ReadBytes(&next_byte, 1);
4038 DCHECK_EQ(0x00, next_byte);
4039 ++frame->num_padding_bytes;
4040 }
4041}
4042
4043bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4044 bool no_message_length,
4045 QuicMessageFrame* frame) {
4046 if (no_message_length) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08004047 quiche::QuicheStringPiece remaining(reader->ReadRemainingPayload());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004048 frame->data = remaining.data();
4049 frame->message_length = remaining.length();
4050 return true;
4051 }
4052
4053 uint64_t message_length;
4054 if (!reader->ReadVarInt62(&message_length)) {
4055 set_detailed_error("Unable to read message length");
4056 return false;
4057 }
4058
dmcardlecf0bfcf2019-12-13 08:08:21 -08004059 quiche::QuicheStringPiece message_piece;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004060 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4061 set_detailed_error("Unable to read message data");
4062 return false;
4063 }
4064
4065 frame->data = message_piece.data();
4066 frame->message_length = message_length;
4067
4068 return true;
4069}
4070
4071// static
dmcardlecf0bfcf2019-12-13 08:08:21 -08004072quiche::QuicheStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004073 QuicTransportVersion version,
4074 const QuicEncryptedPacket& encrypted,
4075 QuicConnectionIdLength destination_connection_id_length,
4076 QuicConnectionIdLength source_connection_id_length,
4077 bool includes_version,
4078 bool includes_diversification_nonce,
4079 QuicPacketNumberLength packet_number_length,
4080 QuicVariableLengthIntegerLength retry_token_length_length,
4081 uint64_t retry_token_length,
4082 QuicVariableLengthIntegerLength length_length) {
4083 // TODO(ianswett): This is identical to QuicData::AssociatedData.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004084 return quiche::QuicheStringPiece(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004085 encrypted.data(),
4086 GetStartOfEncryptedData(version, destination_connection_id_length,
4087 source_connection_id_length, includes_version,
4088 includes_diversification_nonce,
4089 packet_number_length, retry_token_length_length,
4090 retry_token_length, length_length));
4091}
4092
4093void QuicFramer::SetDecrypter(EncryptionLevel level,
4094 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004095 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004096 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004097 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004098 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004099 << EncryptionLevelToString(decrypter_level_) << " to "
4100 << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004101 decrypter_[decrypter_level_] = nullptr;
4102 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004103 decrypter_level_ = level;
4104}
4105
4106void QuicFramer::SetAlternativeDecrypter(
4107 EncryptionLevel level,
4108 std::unique_ptr<QuicDecrypter> decrypter,
4109 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004110 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004111 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004112 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004113 << EncryptionLevelToString(alternative_decrypter_level_)
4114 << " to " << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004115 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4116 decrypter_[alternative_decrypter_level_] = nullptr;
4117 }
4118 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004119 alternative_decrypter_level_ = level;
4120 alternative_decrypter_latch_ = latch_once_used;
4121}
4122
zhongyi546cc452019-04-12 15:27:49 -07004123void QuicFramer::InstallDecrypter(EncryptionLevel level,
4124 std::unique_ptr<QuicDecrypter> decrypter) {
4125 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004126 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004127 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004128 decrypter_[level] = std::move(decrypter);
4129}
4130
4131void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4132 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004133 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004134 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004135 decrypter_[level] = nullptr;
4136}
4137
4138const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4139 DCHECK(version_.KnowsWhichDecrypterToUse());
4140 return decrypter_[level].get();
4141}
4142
QUICHE teama6ef0a62019-03-07 20:34:33 -05004143const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004144 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004145}
4146
4147const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004148 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4149 return nullptr;
4150 }
4151 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004152}
4153
4154void QuicFramer::SetEncrypter(EncryptionLevel level,
4155 std::unique_ptr<QuicEncrypter> encrypter) {
4156 DCHECK_GE(level, 0);
4157 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
dschinazi4b5a68a2019-08-15 15:45:36 -07004158 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004159 << EncryptionLevelToString(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004160 encrypter_[level] = std::move(encrypter);
4161}
4162
fayangb296fb82020-02-11 08:14:28 -08004163void QuicFramer::RemoveEncrypter(EncryptionLevel level) {
4164 QUIC_DVLOG(1) << ENDPOINT << "Removing encrypter of "
4165 << EncryptionLevelToString(level);
4166 encrypter_[level] = nullptr;
4167}
4168
nharper4a5a76c2019-09-13 13:44:37 -07004169void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) {
4170 CrypterPair crypters;
4171 CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id,
4172 &crypters);
4173 encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter);
4174 decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter);
4175}
4176
QUICHE teama6ef0a62019-03-07 20:34:33 -05004177size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4178 QuicPacketNumber packet_number,
4179 size_t ad_len,
4180 size_t total_len,
4181 size_t buffer_len,
4182 char* buffer) {
4183 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004184 if (encrypter_[level] == nullptr) {
4185 QUIC_BUG << ENDPOINT
4186 << "Attempted to encrypt in place without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004187 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004188 RaiseError(QUIC_ENCRYPTION_FAILURE);
4189 return 0;
4190 }
4191
QUICHE teama6ef0a62019-03-07 20:34:33 -05004192 size_t output_length = 0;
4193 if (!encrypter_[level]->EncryptPacket(
4194 packet_number.ToUint64(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08004195 quiche::QuicheStringPiece(buffer, ad_len), // Associated data
4196 quiche::QuicheStringPiece(buffer + ad_len,
4197 total_len - ad_len), // Plaintext
4198 buffer + ad_len, // Destination buffer
QUICHE teama6ef0a62019-03-07 20:34:33 -05004199 &output_length, buffer_len - ad_len)) {
4200 RaiseError(QUIC_ENCRYPTION_FAILURE);
4201 return 0;
4202 }
nharper55fa6132019-05-07 19:37:21 -07004203 if (version_.HasHeaderProtection() &&
4204 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4205 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4206 RaiseError(QUIC_ENCRYPTION_FAILURE);
4207 return 0;
4208 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004209
4210 return ad_len + output_length;
4211}
4212
nharper55fa6132019-05-07 19:37:21 -07004213namespace {
4214
4215const size_t kHPSampleLen = 16;
4216
4217constexpr bool IsLongHeader(uint8_t type_byte) {
4218 return (type_byte & FLAGS_LONG_HEADER) != 0;
4219}
4220
4221} // namespace
4222
4223bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4224 char* buffer,
4225 size_t buffer_len,
4226 size_t ad_len) {
4227 QuicDataReader buffer_reader(buffer, buffer_len);
4228 QuicDataWriter buffer_writer(buffer_len, buffer);
4229 // The sample starts 4 bytes after the start of the packet number.
4230 if (ad_len < last_written_packet_number_length_) {
4231 return false;
4232 }
4233 size_t pn_offset = ad_len - last_written_packet_number_length_;
4234 // Sample the ciphertext and generate the mask to use for header protection.
4235 size_t sample_offset = pn_offset + 4;
4236 QuicDataReader sample_reader(buffer, buffer_len);
dmcardlecf0bfcf2019-12-13 08:08:21 -08004237 quiche::QuicheStringPiece sample;
nharper55fa6132019-05-07 19:37:21 -07004238 if (!sample_reader.Seek(sample_offset) ||
4239 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4240 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4241 << ", sample len: " << kHPSampleLen
4242 << ", buffer len: " << buffer_len;
4243 return false;
4244 }
4245
dschinazida9fafd2020-03-16 15:32:55 -07004246 if (encrypter_[level] == nullptr) {
4247 QUIC_BUG
4248 << ENDPOINT
4249 << "Attempted to apply header protection without encrypter at level "
4250 << EncryptionLevelToString(level) << " using " << version_;
4251 return false;
4252 }
4253
nharper55fa6132019-05-07 19:37:21 -07004254 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4255 if (mask.empty()) {
4256 QUIC_BUG << "Unable to generate header protection mask.";
4257 return false;
4258 }
4259 QuicDataReader mask_reader(mask.data(), mask.size());
4260
4261 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4262 uint8_t bitmask = 0x1f;
4263 uint8_t type_byte;
4264 if (!buffer_reader.ReadUInt8(&type_byte)) {
4265 return false;
4266 }
4267 QuicLongHeaderType header_type;
4268 if (IsLongHeader(type_byte)) {
4269 bitmask = 0x0f;
fayang36825da2019-08-21 14:01:27 -07004270 if (!GetLongHeaderType(type_byte, &header_type)) {
nharper55fa6132019-05-07 19:37:21 -07004271 return false;
4272 }
4273 }
4274 uint8_t mask_byte;
4275 if (!mask_reader.ReadUInt8(&mask_byte) ||
4276 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4277 return false;
4278 }
4279
4280 // Adjust |pn_offset| to account for the diversification nonce.
4281 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4282 perspective_ == Perspective::IS_SERVER &&
4283 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4284 if (pn_offset <= kDiversificationNonceSize) {
4285 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4286 return false;
4287 }
4288 pn_offset -= kDiversificationNonceSize;
4289 }
4290 // Advance the reader and writer to the packet number. Both the reader and
4291 // writer have each read/written one byte.
4292 if (!buffer_writer.Seek(pn_offset - 1) ||
4293 !buffer_reader.Seek(pn_offset - 1)) {
4294 return false;
4295 }
4296 // Apply the rest of the mask to the packet number.
4297 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4298 uint8_t buffer_byte;
4299 uint8_t mask_byte;
4300 if (!mask_reader.ReadUInt8(&mask_byte) ||
4301 !buffer_reader.ReadUInt8(&buffer_byte) ||
4302 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4303 return false;
4304 }
4305 }
4306 return true;
4307}
4308
4309bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4310 const QuicEncryptedPacket& packet,
4311 QuicPacketHeader* header,
4312 uint64_t* full_packet_number,
4313 std::vector<char>* associated_data) {
4314 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4315 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4316 if (decrypter == nullptr) {
4317 QUIC_DVLOG(1)
dschinazi4b5a68a2019-08-15 15:45:36 -07004318 << ENDPOINT
nharper55fa6132019-05-07 19:37:21 -07004319 << "No decrypter available for removing header protection at level "
dschinazief79a5f2019-10-04 10:32:54 -07004320 << EncryptionLevelToString(expected_decryption_level);
nharper55fa6132019-05-07 19:37:21 -07004321 return false;
4322 }
4323
4324 bool has_diversification_nonce =
4325 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4326 header->long_packet_type == ZERO_RTT_PROTECTED &&
4327 perspective_ == Perspective::IS_CLIENT &&
4328 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4329
4330 // Read a sample from the ciphertext and compute the mask to use for header
4331 // protection.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004332 quiche::QuicheStringPiece remaining_packet = reader->PeekRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07004333 QuicDataReader sample_reader(remaining_packet);
4334
4335 // The sample starts 4 bytes after the start of the packet number.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004336 quiche::QuicheStringPiece pn;
nharper55fa6132019-05-07 19:37:21 -07004337 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4338 QUIC_DVLOG(1) << "Not enough data to sample";
4339 return false;
4340 }
4341 if (has_diversification_nonce) {
4342 // In Google QUIC, the diversification nonce comes between the packet number
4343 // and the sample.
4344 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4345 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4346 return false;
4347 }
4348 }
4349 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4350 QuicDataReader mask_reader(mask.data(), mask.size());
4351 if (mask.empty()) {
4352 QUIC_DVLOG(1) << "Failed to compute mask";
4353 return false;
4354 }
4355
4356 // Unmask the rest of the type byte.
4357 uint8_t bitmask = 0x1f;
4358 if (IsLongHeader(header->type_byte)) {
4359 bitmask = 0x0f;
4360 }
4361 uint8_t mask_byte;
4362 if (!mask_reader.ReadUInt8(&mask_byte)) {
4363 QUIC_DVLOG(1) << "No first byte to read from mask";
4364 return false;
4365 }
4366 header->type_byte ^= (mask_byte & bitmask);
4367
4368 // Compute the packet number length.
4369 header->packet_number_length =
4370 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4371
4372 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
bnc4e9283d2019-12-17 07:08:57 -08004373 QuicDataWriter pn_writer(QUICHE_ARRAYSIZE(pn_buffer), pn_buffer);
nharper55fa6132019-05-07 19:37:21 -07004374
4375 // Read the (protected) packet number from the reader and unmask the packet
4376 // number.
4377 for (size_t i = 0; i < header->packet_number_length; ++i) {
4378 uint8_t protected_pn_byte, mask_byte;
4379 if (!mask_reader.ReadUInt8(&mask_byte) ||
4380 !reader->ReadUInt8(&protected_pn_byte) ||
4381 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4382 QUIC_DVLOG(1) << "Failed to unmask packet number";
4383 return false;
4384 }
4385 }
4386 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4387 QuicPacketNumber base_packet_number;
4388 if (supports_multiple_packet_number_spaces_) {
4389 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4390 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4391 return false;
4392 }
4393 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4394 } else {
4395 base_packet_number = largest_packet_number_;
4396 }
4397 if (!ProcessAndCalculatePacketNumber(
4398 &packet_number_reader, header->packet_number_length,
4399 base_packet_number, full_packet_number)) {
4400 return false;
4401 }
4402
4403 // Get the associated data, and apply the same unmasking operations to it.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004404 quiche::QuicheStringPiece ad = GetAssociatedDataFromEncryptedPacket(
nharper55fa6132019-05-07 19:37:21 -07004405 version_.transport_version, packet,
4406 GetIncludedDestinationConnectionIdLength(*header),
4407 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4408 has_diversification_nonce, header->packet_number_length,
4409 header->retry_token_length_length, header->retry_token.length(),
4410 header->length_length);
4411 *associated_data = std::vector<char>(ad.begin(), ad.end());
4412 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4413
4414 // Apply the unmasked type byte and packet number to |associated_data|.
4415 if (!ad_writer.WriteUInt8(header->type_byte)) {
4416 return false;
4417 }
4418 // Put the packet number at the end of the AD, or if there's a diversification
4419 // nonce, before that (which is at the end of the AD).
4420 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4421 if (has_diversification_nonce) {
4422 seek_len -= kDiversificationNonceSize;
4423 }
4424 if (!ad_writer.Seek(seek_len) ||
4425 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4426 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4427 return false;
4428 }
4429
4430 return true;
4431}
4432
QUICHE teama6ef0a62019-03-07 20:34:33 -05004433size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4434 QuicPacketNumber packet_number,
4435 const QuicPacket& packet,
4436 char* buffer,
4437 size_t buffer_len) {
4438 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004439 if (encrypter_[level] == nullptr) {
4440 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004441 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004442 RaiseError(QUIC_ENCRYPTION_FAILURE);
4443 return 0;
4444 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004445
dmcardlecf0bfcf2019-12-13 08:08:21 -08004446 quiche::QuicheStringPiece associated_data =
QUICHE teama6ef0a62019-03-07 20:34:33 -05004447 packet.AssociatedData(version_.transport_version);
4448 // Copy in the header, because the encrypter only populates the encrypted
4449 // plaintext content.
4450 const size_t ad_len = associated_data.length();
4451 memmove(buffer, associated_data.data(), ad_len);
4452 // Encrypt the plaintext into the buffer.
4453 size_t output_length = 0;
4454 if (!encrypter_[level]->EncryptPacket(
4455 packet_number.ToUint64(), associated_data,
4456 packet.Plaintext(version_.transport_version), buffer + ad_len,
4457 &output_length, buffer_len - ad_len)) {
4458 RaiseError(QUIC_ENCRYPTION_FAILURE);
4459 return 0;
4460 }
nharper55fa6132019-05-07 19:37:21 -07004461 if (version_.HasHeaderProtection() &&
4462 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4463 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4464 RaiseError(QUIC_ENCRYPTION_FAILURE);
4465 return 0;
4466 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004467
4468 return ad_len + output_length;
4469}
4470
4471size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4472 size_t plaintext_size) const {
dschinazida9fafd2020-03-16 15:32:55 -07004473 if (encrypter_[level] == nullptr) {
4474 QUIC_BUG << ENDPOINT
4475 << "Attempted to get ciphertext size without encrypter at level "
4476 << EncryptionLevelToString(level) << " using " << version_;
4477 return plaintext_size;
4478 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004479 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4480}
4481
4482size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4483 // In order to keep the code simple, we don't have the current encryption
4484 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4485 size_t min_plaintext_size = ciphertext_size;
4486
QUICHE team6987b4a2019-03-15 16:23:04 -07004487 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004488 if (encrypter_[i] != nullptr) {
4489 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4490 if (size < min_plaintext_size) {
4491 min_plaintext_size = size;
4492 }
4493 }
4494 }
4495
4496 return min_plaintext_size;
4497}
4498
dmcardlecf0bfcf2019-12-13 08:08:21 -08004499bool QuicFramer::DecryptPayload(quiche::QuicheStringPiece encrypted,
4500 quiche::QuicheStringPiece associated_data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004501 const QuicPacketHeader& header,
4502 char* decrypted_buffer,
4503 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004504 size_t* decrypted_length,
4505 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004506 if (!EncryptionLevelIsValid(decrypter_level_)) {
4507 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4508 return false;
4509 }
zhongyi546cc452019-04-12 15:27:49 -07004510 EncryptionLevel level = decrypter_level_;
4511 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004512 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004513 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004514 if (header.form == GOOGLE_QUIC_PACKET) {
4515 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4516 "knows which decrypter to use";
4517 return false;
4518 }
zhongyi546cc452019-04-12 15:27:49 -07004519 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004520 if (!EncryptionLevelIsValid(level)) {
4521 QUIC_BUG << "Attempted to decrypt with bad level";
4522 return false;
4523 }
zhongyi546cc452019-04-12 15:27:49 -07004524 decrypter = decrypter_[level].get();
4525 if (decrypter == nullptr) {
4526 return false;
4527 }
4528 if (level == ENCRYPTION_ZERO_RTT &&
4529 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4530 decrypter->SetDiversificationNonce(*header.nonce);
4531 }
4532 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004533 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4534 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4535 return false;
4536 }
QUICHE team76086e42019-03-25 15:12:29 -07004537 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4538 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004539
nharper855d2172019-05-02 16:17:46 -07004540 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004541 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4542 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004543 return false;
4544 }
zhongyi546cc452019-04-12 15:27:49 -07004545
4546 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004547 header.packet_number.ToUint64(), associated_data, encrypted,
4548 decrypted_buffer, decrypted_length, buffer_length);
4549 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004550 visitor_->OnDecryptedPacket(level);
4551 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004552 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004553 if (header.nonce != nullptr) {
4554 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004555 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004556 }
4557 bool try_alternative_decryption = true;
4558 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4559 if (perspective_ == Perspective::IS_CLIENT) {
4560 if (header.nonce == nullptr) {
4561 // Can not use INITIAL decryption without a diversification nonce.
4562 try_alternative_decryption = false;
4563 }
4564 } else {
4565 DCHECK(header.nonce == nullptr);
4566 }
4567 }
4568
4569 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004570 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004571 header.packet_number.ToUint64(), associated_data, encrypted,
4572 decrypted_buffer, decrypted_length, buffer_length);
4573 }
4574 if (success) {
4575 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004576 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004577 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004578 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4579 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4580 "alternative_decrypter_level_";
4581 return false;
4582 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004583 // Switch to the alternative decrypter and latch so that we cannot
4584 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004585 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004586 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004587 } else {
4588 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004589 EncryptionLevel level = alternative_decrypter_level_;
4590 alternative_decrypter_level_ = decrypter_level_;
4591 decrypter_level_ = level;
4592 }
4593 }
4594 }
4595
4596 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004597 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004598 return false;
4599 }
4600
4601 return true;
4602}
4603
4604size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4605 // Type byte, largest_acked, and delay_time are straight-forward.
4606 size_t ack_frame_size = kQuicFrameTypeSize;
4607 QuicPacketNumber largest_acked = LargestAcked(frame);
4608 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4609 uint64_t ack_delay_time_us;
4610 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004611 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004612 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4613
fayang91c23d72020-03-09 12:35:05 -07004614 if (frame.packets.Empty() || frame.packets.Max() != largest_acked) {
4615 QUIC_BUG << "Malformed ack frame";
4616 // ACK frame serialization will fail and connection will be closed.
4617 return ack_frame_size;
4618 }
4619
4620 // Ack block count.
4621 ack_frame_size +=
4622 QuicDataWriter::GetVarInt62Len(frame.packets.NumIntervals() - 1);
4623
4624 // First Ack range.
4625 auto iter = frame.packets.rbegin();
4626 ack_frame_size += QuicDataWriter::GetVarInt62Len(iter->Length() - 1);
4627 QuicPacketNumber previous_smallest = iter->min();
4628 ++iter;
4629
4630 // Ack blocks.
4631 for (; iter != frame.packets.rend(); ++iter) {
4632 const uint64_t gap = previous_smallest - iter->max() - 1;
4633 const uint64_t ack_range = iter->Length() - 1;
4634 ack_frame_size += (QuicDataWriter::GetVarInt62Len(gap) +
4635 QuicDataWriter::GetVarInt62Len(ack_range));
4636 previous_smallest = iter->min();
4637 }
4638
4639 // ECN counts.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004640 if (frame.ecn_counters_populated &&
4641 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4642 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4643 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4644 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4645 }
4646
QUICHE teama6ef0a62019-03-07 20:34:33 -05004647 return ack_frame_size;
4648}
4649
4650size_t QuicFramer::GetAckFrameSize(
4651 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004652 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004653 DCHECK(!ack.packets.Empty());
4654 size_t ack_size = 0;
4655
fkastenholz305e1732019-06-18 05:01:22 -07004656 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004657 return GetIetfAckFrameSize(ack);
4658 }
4659 AckFrameInfo ack_info = GetAckFrameInfo(ack);
renjietang488201d2019-12-17 13:40:49 -08004660 QuicPacketNumberLength ack_block_length =
4661 GetMinPacketNumberLength(QuicPacketNumber(ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004662
fayang43697fd2020-04-21 11:13:43 -07004663 ack_size = GetMinAckFrameSize(version_.transport_version, ack,
4664 local_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004665 // First ack block length.
4666 ack_size += ack_block_length;
4667 if (ack_info.num_ack_blocks != 0) {
4668 ack_size += kNumberOfAckBlocksSize;
4669 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4670 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4671 }
4672
4673 // Include timestamps.
4674 if (process_timestamps_) {
4675 ack_size += GetAckFrameTimeStampSize(ack);
4676 }
4677
4678 return ack_size;
4679}
4680
4681size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4682 if (ack.received_packet_times.empty()) {
4683 return 0;
4684 }
4685
4686 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4687 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4688 (ack.received_packet_times.size() - 1);
4689}
4690
4691size_t QuicFramer::ComputeFrameLength(
4692 const QuicFrame& frame,
4693 bool last_frame_in_packet,
4694 QuicPacketNumberLength packet_number_length) {
4695 switch (frame.type) {
4696 case STREAM_FRAME:
4697 return GetMinStreamFrameSize(
4698 version_.transport_version, frame.stream_frame.stream_id,
4699 frame.stream_frame.offset, last_frame_in_packet,
4700 frame.stream_frame.data_length) +
4701 frame.stream_frame.data_length;
4702 case CRYPTO_FRAME:
4703 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4704 frame.crypto_frame->data_length) +
4705 frame.crypto_frame->data_length;
4706 case ACK_FRAME: {
4707 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4708 }
4709 case STOP_WAITING_FRAME:
renjietang488201d2019-12-17 13:40:49 -08004710 return GetStopWaitingFrameSize(packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004711 case MTU_DISCOVERY_FRAME:
4712 // MTU discovery frames are serialized as ping frames.
4713 return kQuicFrameTypeSize;
4714 case MESSAGE_FRAME:
4715 return GetMessageFrameSize(version_.transport_version,
4716 last_frame_in_packet,
4717 frame.message_frame->message_length);
4718 case PADDING_FRAME:
4719 DCHECK(false);
4720 return 0;
4721 default:
4722 return GetRetransmittableControlFrameSize(version_.transport_version,
4723 frame);
4724 }
4725}
4726
4727bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4728 bool last_frame_in_packet,
4729 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004730 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004731 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4732 }
4733 uint8_t type_byte = 0;
4734 switch (frame.type) {
4735 case STREAM_FRAME:
4736 type_byte =
4737 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4738 break;
4739 case ACK_FRAME:
4740 return true;
4741 case MTU_DISCOVERY_FRAME:
4742 type_byte = static_cast<uint8_t>(PING_FRAME);
4743 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004744 case NEW_CONNECTION_ID_FRAME:
4745 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004746 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004747 return RaiseError(QUIC_INTERNAL_ERROR);
4748 case RETIRE_CONNECTION_ID_FRAME:
4749 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004750 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004751 return RaiseError(QUIC_INTERNAL_ERROR);
4752 case NEW_TOKEN_FRAME:
4753 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004754 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004755 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004756 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004757 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004758 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004759 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004760 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004761 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004762 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004763 return RaiseError(QUIC_INTERNAL_ERROR);
4764 case PATH_RESPONSE_FRAME:
4765 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004766 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004767 return RaiseError(QUIC_INTERNAL_ERROR);
4768 case PATH_CHALLENGE_FRAME:
4769 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004770 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004771 return RaiseError(QUIC_INTERNAL_ERROR);
4772 case STOP_SENDING_FRAME:
4773 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004774 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004775 return RaiseError(QUIC_INTERNAL_ERROR);
4776 case MESSAGE_FRAME:
4777 return true;
4778
4779 default:
4780 type_byte = static_cast<uint8_t>(frame.type);
4781 break;
4782 }
4783
4784 return writer->WriteUInt8(type_byte);
4785}
4786
4787bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4788 bool last_frame_in_packet,
4789 QuicDataWriter* writer) {
4790 uint8_t type_byte = 0;
4791 switch (frame.type) {
4792 case PADDING_FRAME:
4793 type_byte = IETF_PADDING;
4794 break;
4795 case RST_STREAM_FRAME:
4796 type_byte = IETF_RST_STREAM;
4797 break;
4798 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004799 switch (frame.connection_close_frame->close_type) {
4800 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4801 type_byte = IETF_APPLICATION_CLOSE;
4802 break;
4803 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4804 type_byte = IETF_CONNECTION_CLOSE;
4805 break;
4806 default:
4807 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4808 return RaiseError(QUIC_INTERNAL_ERROR);
4809 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004810 break;
4811 case GOAWAY_FRAME:
4812 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004813 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004814 return RaiseError(QUIC_INTERNAL_ERROR);
4815 case WINDOW_UPDATE_FRAME:
4816 // Depending on whether there is a stream ID or not, will be either a
4817 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4818 if (frame.window_update_frame->stream_id ==
4819 QuicUtils::GetInvalidStreamId(transport_version())) {
4820 type_byte = IETF_MAX_DATA;
4821 } else {
4822 type_byte = IETF_MAX_STREAM_DATA;
4823 }
4824 break;
4825 case BLOCKED_FRAME:
4826 if (frame.blocked_frame->stream_id ==
4827 QuicUtils::GetInvalidStreamId(transport_version())) {
ianswett2f077442019-12-12 11:51:24 -08004828 type_byte = IETF_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004829 } else {
ianswett2f077442019-12-12 11:51:24 -08004830 type_byte = IETF_STREAM_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004831 }
4832 break;
4833 case STOP_WAITING_FRAME:
4834 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004835 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004836 return RaiseError(QUIC_INTERNAL_ERROR);
4837 case PING_FRAME:
4838 type_byte = IETF_PING;
4839 break;
4840 case STREAM_FRAME:
4841 type_byte =
4842 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4843 break;
4844 case ACK_FRAME:
4845 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4846 // in the buffer.
4847 return true;
4848 case MTU_DISCOVERY_FRAME:
4849 // The path MTU discovery frame is encoded as a PING frame on the wire.
4850 type_byte = IETF_PING;
4851 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004852 case NEW_CONNECTION_ID_FRAME:
4853 type_byte = IETF_NEW_CONNECTION_ID;
4854 break;
4855 case RETIRE_CONNECTION_ID_FRAME:
4856 type_byte = IETF_RETIRE_CONNECTION_ID;
4857 break;
4858 case NEW_TOKEN_FRAME:
4859 type_byte = IETF_NEW_TOKEN;
4860 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004861 case MAX_STREAMS_FRAME:
4862 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004863 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004864 } else {
4865 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004866 }
4867 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004868 case STREAMS_BLOCKED_FRAME:
4869 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004870 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004871 } else {
4872 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004873 }
4874 break;
4875 case PATH_RESPONSE_FRAME:
4876 type_byte = IETF_PATH_RESPONSE;
4877 break;
4878 case PATH_CHALLENGE_FRAME:
4879 type_byte = IETF_PATH_CHALLENGE;
4880 break;
4881 case STOP_SENDING_FRAME:
4882 type_byte = IETF_STOP_SENDING;
4883 break;
4884 case MESSAGE_FRAME:
4885 return true;
4886 case CRYPTO_FRAME:
4887 type_byte = IETF_CRYPTO;
4888 break;
fayang01062942020-01-22 07:23:23 -08004889 case HANDSHAKE_DONE_FRAME:
4890 type_byte = IETF_HANDSHAKE_DONE;
4891 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004892 default:
4893 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4894 << frame.type;
4895 return false;
4896 }
4897 return writer->WriteUInt8(type_byte);
4898}
4899
4900// static
4901bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4902 QuicPacketNumber packet_number,
4903 QuicDataWriter* writer) {
4904 DCHECK(packet_number.IsInitialized());
4905 if (!IsValidPacketNumberLength(packet_number_length)) {
4906 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4907 return false;
4908 }
4909 return writer->WriteBytesToUInt64(packet_number_length,
4910 packet_number.ToUint64());
4911}
4912
4913// static
4914bool QuicFramer::AppendStreamId(size_t stream_id_length,
4915 QuicStreamId stream_id,
4916 QuicDataWriter* writer) {
4917 if (stream_id_length == 0 || stream_id_length > 4) {
4918 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4919 return false;
4920 }
4921 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4922}
4923
4924// static
4925bool QuicFramer::AppendStreamOffset(size_t offset_length,
4926 QuicStreamOffset offset,
4927 QuicDataWriter* writer) {
4928 if (offset_length == 1 || offset_length > 8) {
4929 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4930 return false;
4931 }
4932
4933 return writer->WriteBytesToUInt64(offset_length, offset);
4934}
4935
4936// static
4937bool QuicFramer::AppendAckBlock(uint8_t gap,
4938 QuicPacketNumberLength length_length,
4939 uint64_t length,
4940 QuicDataWriter* writer) {
4941 if (length == 0) {
4942 if (!IsValidPacketNumberLength(length_length)) {
4943 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4944 return false;
4945 }
4946 return writer->WriteUInt8(gap) &&
4947 writer->WriteBytesToUInt64(length_length, length);
4948 }
4949 return writer->WriteUInt8(gap) &&
4950 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4951}
4952
4953bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4954 bool no_stream_frame_length,
4955 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004956 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004957 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4958 }
4959 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4960 writer)) {
4961 QUIC_BUG << "Writing stream id size failed.";
4962 return false;
4963 }
renjietang488201d2019-12-17 13:40:49 -08004964 if (!AppendStreamOffset(GetStreamOffsetSize(frame.offset), frame.offset,
4965 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004966 QUIC_BUG << "Writing offset size failed.";
4967 return false;
4968 }
4969 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07004970 static_assert(
wubeff50282019-06-19 09:04:30 -07004971 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07004972 std::numeric_limits<uint16_t>::max(),
4973 "If frame.data_length can hold more than a uint16_t than we need to "
4974 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
4975 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004976 QUIC_BUG << "Writing stream frame length failed";
4977 return false;
4978 }
4979 }
4980
4981 if (data_producer_ != nullptr) {
4982 DCHECK_EQ(nullptr, frame.data_buffer);
4983 if (frame.data_length == 0) {
4984 return true;
4985 }
4986 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
4987 frame.data_length,
4988 writer) != WRITE_SUCCESS) {
4989 QUIC_BUG << "Writing frame data failed.";
4990 return false;
4991 }
4992 return true;
4993 }
4994
4995 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
4996 QUIC_BUG << "Writing frame data failed.";
4997 return false;
4998 }
4999 return true;
5000}
5001
QUICHE teama6ef0a62019-03-07 20:34:33 -05005002bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5003 QuicDataWriter* writer) {
5004 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5005 set_detailed_error("Writing token length failed.");
5006 return false;
5007 }
5008 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5009 set_detailed_error("Writing token buffer failed.");
5010 return false;
5011 }
5012 return true;
5013}
5014
5015bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5016 QuicNewTokenFrame* frame) {
5017 uint64_t length;
5018 if (!reader->ReadVarInt62(&length)) {
5019 set_detailed_error("Unable to read new token length.");
5020 return false;
5021 }
5022 if (length > kMaxNewTokenTokenLength) {
5023 set_detailed_error("Token length larger than maximum.");
5024 return false;
5025 }
5026
dmcardlecf0bfcf2019-12-13 08:08:21 -08005027 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
5028 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005029 if (!reader->ReadStringPiece(&data, length)) {
5030 set_detailed_error("Unable to read new token data.");
5031 return false;
5032 }
vasilvvc48c8712019-03-11 13:38:16 -07005033 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005034 return true;
5035}
5036
5037// Add a new ietf-format stream frame.
5038// Bits controlling whether there is a frame-length and frame-offset
5039// are in the QuicStreamFrame.
5040bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5041 bool last_frame_in_packet,
5042 QuicDataWriter* writer) {
5043 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5044 set_detailed_error("Writing stream id failed.");
5045 return false;
5046 }
5047
5048 if (frame.offset != 0) {
5049 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5050 set_detailed_error("Writing data offset failed.");
5051 return false;
5052 }
5053 }
5054
5055 if (!last_frame_in_packet) {
5056 if (!writer->WriteVarInt62(frame.data_length)) {
5057 set_detailed_error("Writing data length failed.");
5058 return false;
5059 }
5060 }
5061
5062 if (frame.data_length == 0) {
5063 return true;
5064 }
5065 if (data_producer_ == nullptr) {
5066 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5067 set_detailed_error("Writing frame data failed.");
5068 return false;
5069 }
5070 } else {
5071 DCHECK_EQ(nullptr, frame.data_buffer);
5072
5073 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5074 frame.data_length,
5075 writer) != WRITE_SUCCESS) {
5076 set_detailed_error("Writing frame data failed.");
5077 return false;
5078 }
5079 }
5080 return true;
5081}
5082
5083bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5084 QuicDataWriter* writer) {
5085 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5086 set_detailed_error("Writing data offset failed.");
5087 return false;
5088 }
5089 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5090 set_detailed_error("Writing data length failed.");
5091 return false;
5092 }
5093 if (data_producer_ == nullptr) {
5094 if (frame.data_buffer == nullptr ||
5095 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5096 set_detailed_error("Writing frame data failed.");
5097 return false;
5098 }
5099 } else {
5100 DCHECK_EQ(nullptr, frame.data_buffer);
5101 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5102 frame.data_length, writer)) {
5103 return false;
5104 }
5105 }
5106 return true;
5107}
5108
5109void QuicFramer::set_version(const ParsedQuicVersion version) {
5110 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5111 version_ = version;
5112}
5113
5114bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5115 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005116 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005117 return AppendIetfAckFrameAndTypeByte(frame, writer);
5118 }
5119
5120 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5121 QuicPacketNumber largest_acked = LargestAcked(frame);
5122 QuicPacketNumberLength largest_acked_length =
renjietang488201d2019-12-17 13:40:49 -08005123 GetMinPacketNumberLength(largest_acked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005124 QuicPacketNumberLength ack_block_length =
renjietang488201d2019-12-17 13:40:49 -08005125 GetMinPacketNumberLength(QuicPacketNumber(new_ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005126 // Calculate available bytes for timestamps and ack blocks.
5127 int32_t available_timestamp_and_ack_block_bytes =
5128 writer->capacity() - writer->length() - ack_block_length -
fayanga66f6842020-03-06 08:58:55 -08005129 GetMinAckFrameSize(version_.transport_version, frame,
fayang43697fd2020-04-21 11:13:43 -07005130 local_ack_delay_exponent_) -
QUICHE teama6ef0a62019-03-07 20:34:33 -05005131 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5132 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5133
QUICHE teama6ef0a62019-03-07 20:34:33 -05005134 uint8_t type_byte = 0;
5135 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5136 kQuicHasMultipleAckBlocksOffset);
5137
5138 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5139 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5140
5141 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5142 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5143
5144 type_byte |= kQuicFrameTypeAckMask;
5145
5146 if (!writer->WriteUInt8(type_byte)) {
5147 return false;
5148 }
5149
5150 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5151 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5152
5153 // Number of ack blocks.
5154 size_t num_ack_blocks =
5155 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5156 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5157 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5158 }
5159
5160 // Largest acked.
5161 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5162 return false;
5163 }
5164
5165 // Largest acked delta time.
5166 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5167 if (!frame.ack_delay_time.IsInfinite()) {
5168 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5169 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5170 }
5171 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5172 return false;
5173 }
5174
5175 if (num_ack_blocks > 0) {
5176 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5177 return false;
5178 }
5179 }
5180
5181 // First ack block length.
5182 if (!AppendPacketNumber(ack_block_length,
5183 QuicPacketNumber(new_ack_info.first_block_length),
5184 writer)) {
5185 return false;
5186 }
5187
5188 // Ack blocks.
5189 if (num_ack_blocks > 0) {
5190 size_t num_ack_blocks_written = 0;
5191 // Append, in descending order from the largest ACKed packet, a series of
5192 // ACK blocks that represents the successfully acknoweldged packets. Each
5193 // appended gap/block length represents a descending delta from the previous
5194 // block. i.e.:
5195 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5196 // For gaps larger than can be represented by a single encoded gap, a 0
5197 // length gap of the maximum is used, i.e.:
5198 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5199 auto itr = frame.packets.rbegin();
5200 QuicPacketNumber previous_start = itr->min();
5201 ++itr;
5202
5203 for (;
5204 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5205 previous_start = itr->min(), ++itr) {
5206 const auto& interval = *itr;
5207 const uint64_t total_gap = previous_start - interval.max();
5208 const size_t num_encoded_gaps =
5209 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5210 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005211
5212 // Append empty ACK blocks because the gap is longer than a single gap.
5213 for (size_t i = 1;
5214 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5215 ++i) {
5216 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5217 ack_block_length, 0, writer)) {
5218 return false;
5219 }
5220 ++num_ack_blocks_written;
5221 }
5222 if (num_ack_blocks_written >= num_ack_blocks) {
5223 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5224 QUIC_BUG << "Wrote " << num_ack_blocks_written
5225 << ", expected to write " << num_ack_blocks;
5226 }
5227 break;
5228 }
5229
5230 const uint8_t last_gap =
5231 total_gap -
5232 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5233 // Append the final ACK block with a non-empty size.
wub13d75452019-11-05 07:24:56 -08005234 if (!AppendAckBlock(last_gap, ack_block_length, interval.Length(),
5235 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005236 return false;
5237 }
5238 ++num_ack_blocks_written;
5239 }
5240 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5241 }
5242 // Timestamps.
5243 // If we don't process timestamps or if we don't have enough available space
5244 // to append all the timestamps, don't append any of them.
5245 if (process_timestamps_ && writer->capacity() - writer->length() >=
5246 GetAckFrameTimeStampSize(frame)) {
5247 if (!AppendTimestampsToAckFrame(frame, writer)) {
5248 return false;
5249 }
5250 } else {
5251 uint8_t num_received_packets = 0;
5252 if (!writer->WriteBytes(&num_received_packets, 1)) {
5253 return false;
5254 }
5255 }
5256
5257 return true;
5258}
5259
5260bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5261 QuicDataWriter* writer) {
5262 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5263 frame.received_packet_times.size());
5264 // num_received_packets is only 1 byte.
5265 if (frame.received_packet_times.size() >
5266 std::numeric_limits<uint8_t>::max()) {
5267 return false;
5268 }
5269
5270 uint8_t num_received_packets = frame.received_packet_times.size();
5271 if (!writer->WriteBytes(&num_received_packets, 1)) {
5272 return false;
5273 }
5274 if (num_received_packets == 0) {
5275 return true;
5276 }
5277
5278 auto it = frame.received_packet_times.begin();
5279 QuicPacketNumber packet_number = it->first;
5280 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5281
5282 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5283 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5284 return false;
5285 }
5286
5287 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5288 return false;
5289 }
5290
5291 // Use the lowest 4 bytes of the time delta from the creation_time_.
5292 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5293 uint32_t time_delta_us =
5294 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5295 (time_epoch_delta_us - 1));
5296 if (!writer->WriteUInt32(time_delta_us)) {
5297 return false;
5298 }
5299
5300 QuicTime prev_time = it->second;
5301
5302 for (++it; it != frame.received_packet_times.end(); ++it) {
5303 packet_number = it->first;
5304 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5305
5306 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5307 return false;
5308 }
5309
5310 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5311 return false;
5312 }
5313
5314 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5315 prev_time = it->second;
5316 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5317 return false;
5318 }
5319 }
5320 return true;
5321}
5322
5323bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5324 const QuicStopWaitingFrame& frame,
5325 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005326 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
bncbe885272020-01-16 11:10:48 -08005327 DCHECK(frame.least_unacked.IsInitialized());
5328 DCHECK_GE(header.packet_number, frame.least_unacked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005329 const uint64_t least_unacked_delta =
5330 header.packet_number - frame.least_unacked;
5331 const uint64_t length_shift = header.packet_number_length * 8;
5332
5333 if (least_unacked_delta >> length_shift > 0) {
5334 QUIC_BUG << "packet_number_length " << header.packet_number_length
5335 << " is too small for least_unacked_delta: " << least_unacked_delta
5336 << " packet_number:" << header.packet_number
5337 << " least_unacked:" << frame.least_unacked
5338 << " version:" << version_.transport_version;
5339 return false;
5340 }
5341 if (least_unacked_delta == 0) {
5342 return writer->WriteBytesToUInt64(header.packet_number_length,
5343 least_unacked_delta);
5344 }
5345 if (!AppendPacketNumber(header.packet_number_length,
5346 QuicPacketNumber(least_unacked_delta), writer)) {
5347 QUIC_BUG << " seq failed: " << header.packet_number_length;
5348 return false;
5349 }
5350
5351 return true;
5352}
5353
QUICHE teama6ef0a62019-03-07 20:34:33 -05005354bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5355 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005356 uint8_t type = IETF_ACK;
fayang91c23d72020-03-09 12:35:05 -07005357 uint64_t ecn_size = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005358 if (frame.ecn_counters_populated &&
5359 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
fayang91c23d72020-03-09 12:35:05 -07005360 // Change frame type to ACK_ECN if any ECN count is available.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005361 type = IETF_ACK_ECN;
fayang91c23d72020-03-09 12:35:05 -07005362 ecn_size = (QuicDataWriter::GetVarInt62Len(frame.ect_0_count) +
5363 QuicDataWriter::GetVarInt62Len(frame.ect_1_count) +
5364 QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005365 }
5366
5367 if (!writer->WriteUInt8(type)) {
5368 set_detailed_error("No room for frame-type");
5369 return false;
5370 }
5371
5372 QuicPacketNumber largest_acked = LargestAcked(frame);
5373 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5374 set_detailed_error("No room for largest-acked in ack frame");
5375 return false;
5376 }
5377
5378 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5379 if (!frame.ack_delay_time.IsInfinite()) {
5380 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5381 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005382 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005383 }
5384
5385 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5386 set_detailed_error("No room for ack-delay in ack frame");
5387 return false;
5388 }
fayang91c23d72020-03-09 12:35:05 -07005389
5390 if (frame.packets.Empty() || frame.packets.Max() != largest_acked) {
5391 QUIC_BUG << "Malformed ack frame: " << frame;
5392 set_detailed_error("Malformed ack frame");
5393 return false;
5394 }
5395
5396 // Latch ack_block_count for potential truncation.
5397 const uint64_t ack_block_count = frame.packets.NumIntervals() - 1;
5398 QuicDataWriter count_writer(QuicDataWriter::GetVarInt62Len(ack_block_count),
5399 writer->data() + writer->length());
5400 if (!writer->WriteVarInt62(ack_block_count)) {
5401 set_detailed_error("No room for ack block count in ack frame");
5402 return false;
5403 }
5404 auto iter = frame.packets.rbegin();
5405 if (!writer->WriteVarInt62(iter->Length() - 1)) {
5406 set_detailed_error("No room for first ack block in ack frame");
5407 return false;
5408 }
5409 QuicPacketNumber previous_smallest = iter->min();
5410 ++iter;
5411 // Append remaining ACK blocks.
5412 uint64_t appended_ack_blocks = 0;
5413 for (; iter != frame.packets.rend(); ++iter) {
5414 const uint64_t gap = previous_smallest - iter->max() - 1;
5415 const uint64_t ack_range = iter->Length() - 1;
5416
5417 if (writer->remaining() < ecn_size ||
danzh25da9192020-05-01 15:53:28 -07005418 static_cast<size_t>(writer->remaining() - ecn_size) <
fayang91c23d72020-03-09 12:35:05 -07005419 QuicDataWriter::GetVarInt62Len(gap) +
5420 QuicDataWriter::GetVarInt62Len(ack_range)) {
5421 // ACK range does not fit, truncate it.
5422 break;
5423 }
5424 const bool success =
5425 writer->WriteVarInt62(gap) && writer->WriteVarInt62(ack_range);
5426 DCHECK(success);
5427 previous_smallest = iter->min();
5428 ++appended_ack_blocks;
5429 }
5430
5431 if (appended_ack_blocks < ack_block_count) {
5432 // Truncation is needed, rewrite the ack block count.
5433 if (QuicDataWriter::GetVarInt62Len(appended_ack_blocks) !=
5434 QuicDataWriter::GetVarInt62Len(ack_block_count) ||
5435 !count_writer.WriteVarInt62(appended_ack_blocks)) {
5436 // This should never happen as ack_block_count is limited by
5437 // max_ack_ranges_.
5438 QUIC_BUG << "Ack frame truncation fails. ack_block_count: "
5439 << ack_block_count
5440 << ", appended count: " << appended_ack_blocks;
5441 set_detailed_error("ACK frame truncation fails");
5442 return false;
5443 }
5444 QUIC_DLOG(INFO) << ENDPOINT << "ACK ranges get truncated from "
5445 << ack_block_count << " to " << appended_ack_blocks;
5446 }
5447
QUICHE teama6ef0a62019-03-07 20:34:33 -05005448 if (type == IETF_ACK_ECN) {
fayang91c23d72020-03-09 12:35:05 -07005449 // Encode the ECN counts.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005450 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5451 set_detailed_error("No room for ect_0_count in ack frame");
5452 return false;
5453 }
5454 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5455 set_detailed_error("No room for ect_1_count in ack frame");
5456 return false;
5457 }
5458 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5459 set_detailed_error("No room for ecn_ce_count in ack frame");
5460 return false;
5461 }
5462 }
5463
QUICHE teama6ef0a62019-03-07 20:34:33 -05005464 return true;
5465}
5466
5467bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5468 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005469 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005470 return AppendIetfResetStreamFrame(frame, writer);
5471 }
5472 if (!writer->WriteUInt32(frame.stream_id)) {
5473 return false;
5474 }
5475
5476 if (!writer->WriteUInt64(frame.byte_offset)) {
5477 return false;
5478 }
5479
5480 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5481 if (!writer->WriteUInt32(error_code)) {
5482 return false;
5483 }
5484
5485 return true;
5486}
5487
5488bool QuicFramer::AppendConnectionCloseFrame(
5489 const QuicConnectionCloseFrame& frame,
5490 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005491 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005492 return AppendIetfConnectionCloseFrame(frame, writer);
5493 }
bnc77e77b82020-04-05 10:36:49 -07005494 uint32_t error_code = static_cast<uint32_t>(frame.wire_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005495 if (!writer->WriteUInt32(error_code)) {
5496 return false;
5497 }
5498 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5499 return false;
5500 }
5501 return true;
5502}
5503
5504bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5505 QuicDataWriter* writer) {
5506 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5507 if (!writer->WriteUInt32(error_code)) {
5508 return false;
5509 }
5510 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5511 if (!writer->WriteUInt32(stream_id)) {
5512 return false;
5513 }
5514 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5515 return false;
5516 }
5517 return true;
5518}
5519
5520bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5521 QuicDataWriter* writer) {
5522 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5523 if (!writer->WriteUInt32(stream_id)) {
5524 return false;
5525 }
renjietangd088eab2019-11-21 14:54:41 -08005526 if (!writer->WriteUInt64(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005527 return false;
5528 }
5529 return true;
5530}
5531
5532bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5533 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005534 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005535 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
renjietangf8a9c8c2020-03-19 16:47:03 -07005536 return AppendDataBlockedFrame(frame, writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005537 }
renjietangf8a9c8c2020-03-19 16:47:03 -07005538 return AppendStreamDataBlockedFrame(frame, writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005539 }
5540 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5541 if (!writer->WriteUInt32(stream_id)) {
5542 return false;
5543 }
5544 return true;
5545}
5546
5547bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5548 QuicDataWriter* writer) {
5549 if (frame.num_padding_bytes == 0) {
5550 return false;
5551 }
5552 if (frame.num_padding_bytes < 0) {
5553 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5554 writer->WritePadding();
5555 return true;
5556 }
5557 // Please note, num_padding_bytes includes type byte which has been written.
5558 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5559}
5560
5561bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5562 bool last_frame_in_packet,
5563 QuicDataWriter* writer) {
dschinazicd86dd12019-11-14 10:11:13 -08005564 uint8_t type_byte;
5565 if (VersionHasIetfQuicFrames(version_.transport_version)) {
5566 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH_V99
5567 : IETF_EXTENSION_MESSAGE_V99;
5568 } else {
5569 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5570 : IETF_EXTENSION_MESSAGE;
5571 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005572 if (!writer->WriteUInt8(type_byte)) {
5573 return false;
5574 }
5575 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5576 return false;
5577 }
5578 for (const auto& slice : frame.message_data) {
5579 if (!writer->WriteBytes(slice.data(), slice.length())) {
5580 return false;
5581 }
5582 }
5583 return true;
5584}
5585
5586bool QuicFramer::RaiseError(QuicErrorCode error) {
5587 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5588 << " detail: " << detailed_error_;
5589 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005590 if (visitor_) {
5591 visitor_->OnError(this);
5592 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005593 return false;
5594}
5595
5596bool QuicFramer::IsVersionNegotiation(
5597 const QuicPacketHeader& header,
5598 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005599 if (!packet_has_ietf_packet_header &&
5600 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005601 return header.version_flag;
5602 }
5603 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5604 return false;
5605 }
5606 return header.long_packet_type == VERSION_NEGOTIATION;
5607}
5608
QUICHE teama6ef0a62019-03-07 20:34:33 -05005609bool QuicFramer::AppendIetfConnectionCloseFrame(
5610 const QuicConnectionCloseFrame& frame,
5611 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005612 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5613 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5614 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5615 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5616 return false;
5617 }
5618
bnc77e77b82020-04-05 10:36:49 -07005619 if (!writer->WriteVarInt62(frame.wire_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005620 set_detailed_error("Can not write connection close frame error code");
5621 return false;
5622 }
fkastenholze9d71a82019-04-09 05:12:13 -07005623
fkastenholz72f509b2019-04-10 09:17:49 -07005624 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5625 // Write the frame-type of the frame causing the error only
5626 // if it's a CONNECTION_CLOSE/Transport.
5627 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5628 set_detailed_error("Writing frame type failed.");
5629 return false;
5630 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005631 }
5632
fkastenholzb4dade72019-08-05 06:54:20 -07005633 // There may be additional error information available in the extracted error
5634 // code. Encode the error information in the reason phrase and serialize the
5635 // result.
5636 std::string final_error_string =
bnc77e77b82020-04-05 10:36:49 -07005637 GenerateErrorString(frame.error_details, frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005638 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005639 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005640 set_detailed_error("Can not write connection close phrase");
5641 return false;
5642 }
5643 return true;
5644}
5645
QUICHE teama6ef0a62019-03-07 20:34:33 -05005646bool QuicFramer::ProcessIetfConnectionCloseFrame(
5647 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005648 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005649 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005650 frame->close_type = type;
fkastenholzb4dade72019-08-05 06:54:20 -07005651
fkastenholz88d08f42019-09-06 07:38:04 -07005652 uint64_t error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005653 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005654 set_detailed_error("Unable to read connection close error code.");
5655 return false;
5656 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005657
bnc77e77b82020-04-05 10:36:49 -07005658 frame->wire_error_code = error_code;
fkastenholzb4dade72019-08-05 06:54:20 -07005659
fkastenholz72f509b2019-04-10 09:17:49 -07005660 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5661 // The frame-type of the frame causing the error is present only
5662 // if it's a CONNECTION_CLOSE/Transport.
5663 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5664 set_detailed_error("Unable to read connection close frame type.");
5665 return false;
5666 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005667 }
5668
5669 uint64_t phrase_length;
5670 if (!reader->ReadVarInt62(&phrase_length)) {
5671 set_detailed_error("Unable to read connection close error details.");
5672 return false;
5673 }
fkastenholzb4dade72019-08-05 06:54:20 -07005674
dmcardlecf0bfcf2019-12-13 08:08:21 -08005675 quiche::QuicheStringPiece phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005676 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5677 set_detailed_error("Unable to read connection close error details.");
5678 return false;
5679 }
vasilvvc48c8712019-03-11 13:38:16 -07005680 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005681
fkastenholzb4dade72019-08-05 06:54:20 -07005682 // The frame may have an extracted error code in it. Look for it and
5683 // extract it. If it's not present, MaybeExtract will return
5684 // QUIC_IETF_GQUIC_ERROR_MISSING.
fkastenholz488a4622019-08-26 06:24:46 -07005685 MaybeExtractQuicErrorCode(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005686 return true;
5687}
5688
5689// IETF Quic Path Challenge/Response frames.
5690bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5691 QuicPathChallengeFrame* frame) {
5692 if (!reader->ReadBytes(frame->data_buffer.data(),
5693 frame->data_buffer.size())) {
5694 set_detailed_error("Can not read path challenge data.");
5695 return false;
5696 }
5697 return true;
5698}
5699
5700bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5701 QuicPathResponseFrame* frame) {
5702 if (!reader->ReadBytes(frame->data_buffer.data(),
5703 frame->data_buffer.size())) {
5704 set_detailed_error("Can not read path response data.");
5705 return false;
5706 }
5707 return true;
5708}
5709
5710bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5711 QuicDataWriter* writer) {
5712 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5713 set_detailed_error("Writing Path Challenge data failed.");
5714 return false;
5715 }
5716 return true;
5717}
5718
5719bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5720 QuicDataWriter* writer) {
5721 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5722 set_detailed_error("Writing Path Response data failed.");
5723 return false;
5724 }
5725 return true;
5726}
5727
5728// Add a new ietf-format stream reset frame.
5729// General format is
5730// stream id
5731// application error code
5732// final offset
5733bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5734 QuicDataWriter* writer) {
5735 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5736 set_detailed_error("Writing reset-stream stream id failed.");
5737 return false;
5738 }
fkastenholz07300e52019-07-16 11:51:37 -07005739 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005740 set_detailed_error("Writing reset-stream error code failed.");
5741 return false;
5742 }
5743 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5744 set_detailed_error("Writing reset-stream final-offset failed.");
5745 return false;
5746 }
5747 return true;
5748}
5749
5750bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5751 QuicRstStreamFrame* frame) {
5752 // Get Stream ID from frame. ReadVarIntStreamID returns false
5753 // if either A) there is a read error or B) the resulting value of
5754 // the Stream ID is larger than the maximum allowed value.
renjietangd077f8c2020-03-23 17:22:09 -07005755 if (!ReadUint32FromVarint62(reader, IETF_RST_STREAM, &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005756 return false;
5757 }
5758
bnc1b5ac122020-04-10 07:03:37 -07005759 if (!reader->ReadVarInt62(&frame->ietf_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005760 set_detailed_error("Unable to read rst stream error code.");
5761 return false;
5762 }
bnc1b5ac122020-04-10 07:03:37 -07005763
bnc1b5ac122020-04-10 07:03:37 -07005764 frame->error_code =
bnccb0ffbc2020-04-13 10:53:11 -07005765 IetfResetStreamErrorCodeToRstStreamErrorCode(frame->ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005766
5767 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5768 set_detailed_error("Unable to read rst stream sent byte offset.");
5769 return false;
5770 }
5771 return true;
5772}
5773
5774bool QuicFramer::ProcessStopSendingFrame(
5775 QuicDataReader* reader,
5776 QuicStopSendingFrame* stop_sending_frame) {
renjietangd077f8c2020-03-23 17:22:09 -07005777 if (!ReadUint32FromVarint62(reader, IETF_STOP_SENDING,
5778 &stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005779 return false;
5780 }
5781
fkastenholz733552e2019-07-16 11:16:58 -07005782 uint64_t error_code;
5783 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005784 set_detailed_error("Unable to read stop sending application error code.");
5785 return false;
5786 }
fkastenholz733552e2019-07-16 11:16:58 -07005787 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5788 if (error_code > 0xffff) {
5789 stop_sending_frame->application_error_code = 0xffff;
5790 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5791 << ") > 0xffff";
5792 } else {
5793 stop_sending_frame->application_error_code =
5794 static_cast<uint16_t>(error_code);
5795 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005796 return true;
5797}
5798
5799bool QuicFramer::AppendStopSendingFrame(
5800 const QuicStopSendingFrame& stop_sending_frame,
5801 QuicDataWriter* writer) {
5802 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5803 set_detailed_error("Can not write stop sending stream id");
5804 return false;
5805 }
fkastenholz733552e2019-07-16 11:16:58 -07005806 if (!writer->WriteVarInt62(
5807 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005808 set_detailed_error("Can not write application error code");
5809 return false;
5810 }
5811 return true;
5812}
5813
5814// Append/process IETF-Format MAX_DATA Frame
5815bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5816 QuicDataWriter* writer) {
renjietangd088eab2019-11-21 14:54:41 -08005817 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005818 set_detailed_error("Can not write MAX_DATA byte-offset");
5819 return false;
5820 }
5821 return true;
5822}
5823
5824bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5825 QuicWindowUpdateFrame* frame) {
5826 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
renjietangd088eab2019-11-21 14:54:41 -08005827 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005828 set_detailed_error("Can not read MAX_DATA byte-offset");
5829 return false;
5830 }
5831 return true;
5832}
5833
5834// Append/process IETF-Format MAX_STREAM_DATA Frame
5835bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5836 QuicDataWriter* writer) {
5837 if (!writer->WriteVarInt62(frame.stream_id)) {
5838 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5839 return false;
5840 }
renjietangd088eab2019-11-21 14:54:41 -08005841 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005842 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5843 return false;
5844 }
5845 return true;
5846}
5847
5848bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5849 QuicWindowUpdateFrame* frame) {
renjietangd077f8c2020-03-23 17:22:09 -07005850 if (!ReadUint32FromVarint62(reader, IETF_MAX_STREAM_DATA,
5851 &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005852 return false;
5853 }
renjietangd088eab2019-11-21 14:54:41 -08005854 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005855 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5856 return false;
5857 }
5858 return true;
5859}
5860
fkastenholz3c4eabf2019-04-22 07:49:59 -07005861bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005862 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005863 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005864 set_detailed_error("Can not write MAX_STREAMS stream count");
5865 return false;
5866 }
5867 return true;
5868}
5869
5870bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005871 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005872 uint64_t frame_type) {
renjietangd077f8c2020-03-23 17:22:09 -07005873 if (!ReadUint32FromVarint62(reader,
5874 static_cast<QuicIetfFrameType>(frame_type),
5875 &frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005876 return false;
5877 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005878 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
5879 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005880}
5881
renjietangf8a9c8c2020-03-19 16:47:03 -07005882bool QuicFramer::AppendDataBlockedFrame(const QuicBlockedFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005883 QuicDataWriter* writer) {
5884 if (!writer->WriteVarInt62(frame.offset)) {
5885 set_detailed_error("Can not write blocked offset.");
5886 return false;
5887 }
5888 return true;
5889}
5890
renjietangf8a9c8c2020-03-19 16:47:03 -07005891bool QuicFramer::ProcessDataBlockedFrame(QuicDataReader* reader,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005892 QuicBlockedFrame* frame) {
5893 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
5894 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5895 if (!reader->ReadVarInt62(&frame->offset)) {
5896 set_detailed_error("Can not read blocked offset.");
5897 return false;
5898 }
5899 return true;
5900}
5901
renjietangf8a9c8c2020-03-19 16:47:03 -07005902bool QuicFramer::AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame,
5903 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005904 if (!writer->WriteVarInt62(frame.stream_id)) {
5905 set_detailed_error("Can not write stream blocked stream id.");
5906 return false;
5907 }
5908 if (!writer->WriteVarInt62(frame.offset)) {
5909 set_detailed_error("Can not write stream blocked offset.");
5910 return false;
5911 }
5912 return true;
5913}
5914
renjietangf8a9c8c2020-03-19 16:47:03 -07005915bool QuicFramer::ProcessStreamDataBlockedFrame(QuicDataReader* reader,
5916 QuicBlockedFrame* frame) {
renjietangd077f8c2020-03-23 17:22:09 -07005917 if (!ReadUint32FromVarint62(reader, IETF_STREAM_DATA_BLOCKED,
5918 &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005919 return false;
5920 }
5921 if (!reader->ReadVarInt62(&frame->offset)) {
5922 set_detailed_error("Can not read stream blocked offset.");
5923 return false;
5924 }
5925 return true;
5926}
5927
fkastenholz3c4eabf2019-04-22 07:49:59 -07005928bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
5929 QuicDataWriter* writer) {
5930 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005931 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
5932 return false;
5933 }
5934 return true;
5935}
5936
5937bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005938 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005939 uint64_t frame_type) {
renjietangd077f8c2020-03-23 17:22:09 -07005940 if (!ReadUint32FromVarint62(reader,
5941 static_cast<QuicIetfFrameType>(frame_type),
5942 &frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005943 return false;
5944 }
renjietangb885a122020-03-20 08:24:16 -07005945 if (frame->stream_count > QuicUtils::GetMaxStreamCount()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005946 // If stream count is such that the resulting stream ID would exceed our
5947 // implementation limit, generate an error.
5948 set_detailed_error(
5949 "STREAMS_BLOCKED stream count exceeds implementation limit.");
5950 return false;
5951 }
renjietangb885a122020-03-20 08:24:16 -07005952 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
fkastenholz3c4eabf2019-04-22 07:49:59 -07005953 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005954}
5955
5956bool QuicFramer::AppendNewConnectionIdFrame(
5957 const QuicNewConnectionIdFrame& frame,
5958 QuicDataWriter* writer) {
5959 if (!writer->WriteVarInt62(frame.sequence_number)) {
5960 set_detailed_error("Can not write New Connection ID sequence number");
5961 return false;
5962 }
fkastenholz1c19fc22019-07-12 11:06:19 -07005963 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
5964 set_detailed_error("Can not write New Connection ID retire_prior_to");
5965 return false;
5966 }
dschinazicf5b1e22019-07-17 18:35:17 -07005967 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005968 set_detailed_error("Can not write New Connection ID frame connection ID");
5969 return false;
5970 }
5971
5972 if (!writer->WriteBytes(
5973 static_cast<const void*>(&frame.stateless_reset_token),
5974 sizeof(frame.stateless_reset_token))) {
5975 set_detailed_error("Can not write New Connection ID Reset Token");
5976 return false;
5977 }
5978 return true;
5979}
5980
5981bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
5982 QuicNewConnectionIdFrame* frame) {
5983 if (!reader->ReadVarInt62(&frame->sequence_number)) {
5984 set_detailed_error(
5985 "Unable to read new connection ID frame sequence number.");
5986 return false;
5987 }
5988
fkastenholz1c19fc22019-07-12 11:06:19 -07005989 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
5990 set_detailed_error(
5991 "Unable to read new connection ID frame retire_prior_to.");
5992 return false;
5993 }
5994 if (frame->retire_prior_to > frame->sequence_number) {
5995 set_detailed_error("Retire_prior_to > sequence_number.");
5996 return false;
5997 }
dschinazicf5b1e22019-07-17 18:35:17 -07005998
5999 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6000 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006001 return false;
6002 }
6003
dschinazicf5b1e22019-07-17 18:35:17 -07006004 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6005 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006006 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006007 return false;
6008 }
6009
QUICHE teama6ef0a62019-03-07 20:34:33 -05006010 if (!reader->ReadBytes(&frame->stateless_reset_token,
6011 sizeof(frame->stateless_reset_token))) {
6012 set_detailed_error("Can not read new connection ID frame reset token.");
6013 return false;
6014 }
6015 return true;
6016}
6017
6018bool QuicFramer::AppendRetireConnectionIdFrame(
6019 const QuicRetireConnectionIdFrame& frame,
6020 QuicDataWriter* writer) {
6021 if (!writer->WriteVarInt62(frame.sequence_number)) {
6022 set_detailed_error("Can not write Retire Connection ID sequence number");
6023 return false;
6024 }
6025 return true;
6026}
6027
6028bool QuicFramer::ProcessRetireConnectionIdFrame(
6029 QuicDataReader* reader,
6030 QuicRetireConnectionIdFrame* frame) {
6031 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6032 set_detailed_error(
6033 "Unable to read retire connection ID frame sequence number.");
6034 return false;
6035 }
6036 return true;
6037}
6038
renjietangd077f8c2020-03-23 17:22:09 -07006039bool QuicFramer::ReadUint32FromVarint62(QuicDataReader* reader,
6040 QuicIetfFrameType type,
6041 QuicStreamId* id) {
6042 uint64_t temp_uint64;
6043 if (!reader->ReadVarInt62(&temp_uint64)) {
6044 set_detailed_error("Unable to read " + QuicIetfFrameTypeString(type) +
6045 " frame stream id/count.");
6046 return false;
6047 }
6048 if (temp_uint64 > kMaxQuicStreamId) {
6049 set_detailed_error("Stream id/count of " + QuicIetfFrameTypeString(type) +
6050 "frame is too large.");
6051 return false;
6052 }
6053 *id = static_cast<uint32_t>(temp_uint64);
6054 return true;
6055}
6056
QUICHE teama6ef0a62019-03-07 20:34:33 -05006057uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6058 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006059 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006060 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6061 }
6062 uint8_t type_byte = 0;
6063 // Fin bit.
6064 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6065
6066 // Data Length bit.
6067 type_byte <<= kQuicStreamDataLengthShift;
6068 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6069
6070 // Offset 3 bits.
6071 type_byte <<= kQuicStreamShift;
renjietang488201d2019-12-17 13:40:49 -08006072 const size_t offset_len = GetStreamOffsetSize(frame.offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006073 if (offset_len > 0) {
6074 type_byte |= offset_len - 1;
6075 }
6076
6077 // stream id 2 bits.
6078 type_byte <<= kQuicStreamIdShift;
6079 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6080 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6081
6082 return type_byte;
6083}
6084
6085uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6086 const QuicStreamFrame& frame,
6087 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006088 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006089 uint8_t type_byte = IETF_STREAM;
6090 if (!last_frame_in_packet) {
6091 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6092 }
6093 if (frame.offset != 0) {
6094 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6095 }
6096 if (frame.fin) {
6097 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6098 }
6099 return type_byte;
6100}
6101
6102void QuicFramer::InferPacketHeaderTypeFromVersion() {
6103 // This function should only be called when server connection negotiates the
6104 // version.
bncbe885272020-01-16 11:10:48 -08006105 DCHECK_EQ(perspective_, Perspective::IS_SERVER);
6106 DCHECK(!infer_packet_header_type_from_version_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006107 infer_packet_header_type_from_version_ = true;
6108}
6109
QUICHE team10b22a12019-03-21 15:31:42 -07006110void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6111 if (supports_multiple_packet_number_spaces_) {
6112 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6113 return;
6114 }
6115 if (largest_packet_number_.IsInitialized()) {
6116 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6117 "packet has been received.";
6118 return;
6119 }
6120
6121 supports_multiple_packet_number_spaces_ = true;
6122}
6123
fayangccbab732019-05-13 10:11:25 -07006124// static
dschinazi48ac9192019-07-31 00:07:26 -07006125QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6126 const QuicEncryptedPacket& packet,
6127 uint8_t expected_destination_connection_id_length,
6128 PacketHeaderFormat* format,
fayange3f2f7b2019-09-19 17:01:57 -07006129 QuicLongHeaderType* long_packet_type,
dschinazi48ac9192019-07-31 00:07:26 -07006130 bool* version_present,
6131 bool* has_length_prefix,
6132 QuicVersionLabel* version_label,
6133 ParsedQuicVersion* parsed_version,
6134 QuicConnectionId* destination_connection_id,
6135 QuicConnectionId* source_connection_id,
6136 bool* retry_token_present,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006137 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006138 std::string* detailed_error) {
6139 QuicDataReader reader(packet.data(), packet.length());
6140 if (reader.IsDoneReading()) {
6141 *detailed_error = "Unable to read first byte.";
6142 return QUIC_INVALID_PACKET_HEADER;
6143 }
6144 const uint8_t first_byte = reader.PeekByte();
6145 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6146 uint8_t unused_first_byte;
6147 QuicVariableLengthIntegerLength retry_token_length_length;
fayange3f2f7b2019-09-19 17:01:57 -07006148 QuicErrorCode error_code = ParsePublicHeader(
dschinazi48ac9192019-07-31 00:07:26 -07006149 &reader, expected_destination_connection_id_length, ietf_format,
6150 &unused_first_byte, format, version_present, has_length_prefix,
6151 version_label, parsed_version, destination_connection_id,
fayange3f2f7b2019-09-19 17:01:57 -07006152 source_connection_id, long_packet_type, &retry_token_length_length,
dschinazi48ac9192019-07-31 00:07:26 -07006153 retry_token, detailed_error);
6154 *retry_token_present =
6155 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6156 return error_code;
6157}
6158
6159// static
6160QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6161 QuicDataReader* reader,
6162 uint8_t* first_byte,
6163 PacketHeaderFormat* format,
6164 bool* version_present,
6165 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006166 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006167 QuicConnectionId* destination_connection_id,
6168 std::string* detailed_error) {
6169 *format = GOOGLE_QUIC_PACKET;
6170 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6171 uint8_t destination_connection_id_length = 0;
6172 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6173 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6174 }
6175 if (!reader->ReadConnectionId(destination_connection_id,
6176 destination_connection_id_length)) {
6177 *detailed_error = "Unable to read ConnectionId.";
6178 return QUIC_INVALID_PACKET_HEADER;
6179 }
dschinazi243eabc2019-08-05 16:15:29 -07006180 if (*version_present) {
6181 if (!ProcessVersionLabel(reader, version_label)) {
6182 *detailed_error = "Unable to read protocol version.";
6183 return QUIC_INVALID_PACKET_HEADER;
6184 }
6185 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006186 }
6187 return QUIC_NO_ERROR;
6188}
6189
6190namespace {
6191
dschinazi81eb4e02019-09-27 17:12:17 -07006192const QuicVersionLabel kProxVersionLabel = 0x50524F58; // "PROX"
6193
dschinazi48ac9192019-07-31 00:07:26 -07006194inline bool PacketHasLengthPrefixedConnectionIds(
6195 const QuicDataReader& reader,
6196 ParsedQuicVersion parsed_version,
6197 QuicVersionLabel version_label,
6198 uint8_t first_byte) {
6199 if (parsed_version.transport_version != QUIC_VERSION_UNSUPPORTED) {
6200 return parsed_version.HasLengthPrefixedConnectionIds();
6201 }
6202
6203 // Received unsupported version, check known old unsupported versions.
6204 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6205 return false;
6206 }
6207
6208 // Received unknown version, check connection ID length byte.
6209 if (reader.IsDoneReading()) {
6210 // This check is required to safely peek the connection ID length byte.
6211 return true;
6212 }
6213 const uint8_t connection_id_length_byte = reader.PeekByte();
6214
6215 // Check for packets produced by older versions of
6216 // QuicFramer::WriteClientVersionNegotiationProbePacket
6217 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6218 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6219 return false;
6220 }
6221
6222 // Check for munged packets with version tag PROX.
6223 if ((connection_id_length_byte & 0x0f) == 0 &&
dschinazi81eb4e02019-09-27 17:12:17 -07006224 connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) {
dschinazi48ac9192019-07-31 00:07:26 -07006225 return false;
6226 }
6227
6228 return true;
6229}
6230
6231inline bool ParseLongHeaderConnectionIds(
6232 QuicDataReader* reader,
6233 bool has_length_prefix,
dschinazi81eb4e02019-09-27 17:12:17 -07006234 QuicVersionLabel version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006235 QuicConnectionId* destination_connection_id,
6236 QuicConnectionId* source_connection_id,
6237 std::string* detailed_error) {
6238 if (has_length_prefix) {
6239 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6240 *detailed_error = "Unable to read destination connection ID.";
6241 return false;
6242 }
6243 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
dschinazi68fad8e2019-11-04 10:07:21 -08006244 if (version_label == kProxVersionLabel) {
dschinazi81eb4e02019-09-27 17:12:17 -07006245 // The "PROX" version does not follow the length-prefixed invariants,
6246 // and can therefore attempt to read a payload byte and interpret it
6247 // as the source connection ID length, which could fail to parse.
6248 // In that scenario we keep the source connection ID empty but mark
6249 // parsing as successful.
6250 return true;
6251 }
dschinazi48ac9192019-07-31 00:07:26 -07006252 *detailed_error = "Unable to read source connection ID.";
6253 return false;
6254 }
6255 } else {
6256 // Parse connection ID lengths.
6257 uint8_t connection_id_lengths_byte;
6258 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6259 *detailed_error = "Unable to read connection ID lengths.";
6260 return false;
6261 }
6262 uint8_t destination_connection_id_length =
6263 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6264 if (destination_connection_id_length != 0) {
6265 destination_connection_id_length += kConnectionIdLengthAdjustment;
6266 }
6267 uint8_t source_connection_id_length =
6268 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6269 if (source_connection_id_length != 0) {
6270 source_connection_id_length += kConnectionIdLengthAdjustment;
6271 }
6272
6273 // Read destination connection ID.
6274 if (!reader->ReadConnectionId(destination_connection_id,
6275 destination_connection_id_length)) {
6276 *detailed_error = "Unable to read destination connection ID.";
6277 return false;
6278 }
6279
6280 // Read source connection ID.
6281 if (!reader->ReadConnectionId(source_connection_id,
6282 source_connection_id_length)) {
6283 *detailed_error = "Unable to read source connection ID.";
6284 return false;
6285 }
6286 }
6287 return true;
6288}
6289
6290} // namespace
6291
6292// static
6293QuicErrorCode QuicFramer::ParsePublicHeader(
6294 QuicDataReader* reader,
6295 uint8_t expected_destination_connection_id_length,
6296 bool ietf_format,
6297 uint8_t* first_byte,
6298 PacketHeaderFormat* format,
6299 bool* version_present,
6300 bool* has_length_prefix,
6301 QuicVersionLabel* version_label,
6302 ParsedQuicVersion* parsed_version,
6303 QuicConnectionId* destination_connection_id,
6304 QuicConnectionId* source_connection_id,
6305 QuicLongHeaderType* long_packet_type,
6306 QuicVariableLengthIntegerLength* retry_token_length_length,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006307 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006308 std::string* detailed_error) {
6309 *version_present = false;
6310 *has_length_prefix = false;
6311 *version_label = 0;
6312 *parsed_version = UnsupportedQuicVersion();
6313 *source_connection_id = EmptyQuicConnectionId();
6314 *long_packet_type = INVALID_PACKET_TYPE;
6315 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006316 *retry_token = quiche::QuicheStringPiece();
dschinazi48ac9192019-07-31 00:07:26 -07006317 *detailed_error = "";
6318
6319 if (!reader->ReadUInt8(first_byte)) {
6320 *detailed_error = "Unable to read first byte.";
6321 return QUIC_INVALID_PACKET_HEADER;
6322 }
6323
6324 if (!ietf_format) {
6325 return ParsePublicHeaderGoogleQuic(
6326 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006327 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006328 }
6329
6330 *format = GetIetfPacketHeaderFormat(*first_byte);
6331
6332 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6333 // Read destination connection ID using
6334 // expected_destination_connection_id_length to determine its length.
6335 if (!reader->ReadConnectionId(destination_connection_id,
6336 expected_destination_connection_id_length)) {
6337 *detailed_error = "Unable to read destination connection ID.";
6338 return QUIC_INVALID_PACKET_HEADER;
6339 }
6340 return QUIC_NO_ERROR;
6341 }
6342
6343 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6344 *version_present = true;
6345 if (!ProcessVersionLabel(reader, version_label)) {
6346 *detailed_error = "Unable to read protocol version.";
6347 return QUIC_INVALID_PACKET_HEADER;
6348 }
6349
6350 if (*version_label == 0) {
6351 *long_packet_type = VERSION_NEGOTIATION;
6352 }
6353
6354 // Parse version.
6355 *parsed_version = ParseQuicVersionLabel(*version_label);
6356
6357 // Figure out which IETF QUIC invariants this packet follows.
6358 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6359 *reader, *parsed_version, *version_label, *first_byte);
6360
6361 // Parse connection IDs.
dschinazi81eb4e02019-09-27 17:12:17 -07006362 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix, *version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006363 destination_connection_id,
6364 source_connection_id, detailed_error)) {
6365 return QUIC_INVALID_PACKET_HEADER;
6366 }
6367
6368 if (parsed_version->transport_version == QUIC_VERSION_UNSUPPORTED) {
6369 // Skip parsing of long packet type and retry token for unknown versions.
6370 return QUIC_NO_ERROR;
6371 }
6372
6373 // Parse long packet type.
fayang36825da2019-08-21 14:01:27 -07006374 if (!GetLongHeaderType(*first_byte, long_packet_type)) {
dschinazi48ac9192019-07-31 00:07:26 -07006375 *detailed_error = "Unable to parse long packet type.";
6376 return QUIC_INVALID_PACKET_HEADER;
6377 }
6378
6379 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6380 // Retry token is only present on initial packets for some versions.
6381 return QUIC_NO_ERROR;
6382 }
6383
6384 *retry_token_length_length = reader->PeekVarInt62Length();
6385 uint64_t retry_token_length;
6386 if (!reader->ReadVarInt62(&retry_token_length)) {
6387 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6388 *detailed_error = "Unable to read retry token length.";
6389 return QUIC_INVALID_PACKET_HEADER;
6390 }
6391
6392 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6393 *detailed_error = "Unable to read retry token.";
6394 return QUIC_INVALID_PACKET_HEADER;
6395 }
6396
6397 return QUIC_NO_ERROR;
6398}
6399
6400// static
dschinazide0f6dc2019-05-15 16:10:11 -07006401bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6402 char* packet_bytes,
6403 QuicByteCount packet_length,
6404 const char* destination_connection_id_bytes,
6405 uint8_t destination_connection_id_length) {
6406 if (packet_bytes == nullptr) {
6407 QUIC_BUG << "Invalid packet_bytes";
6408 return false;
6409 }
6410 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6411 packet_length > 65535) {
6412 QUIC_BUG << "Invalid packet_length";
6413 return false;
6414 }
dschinazib012d212019-08-01 18:07:26 -07006415 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006416 destination_connection_id_length <
6417 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006418 QUIC_BUG << "Invalid connection_id_length";
6419 return false;
6420 }
dschinazi48ac9192019-07-31 00:07:26 -07006421 const bool use_length_prefix =
6422 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6423 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006424 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006425 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006426 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6427 0xc0,
6428 // Version, part of the IETF space reserved for negotiation.
6429 // This intentionally differs from QuicVersionReservedForNegotiation()
6430 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006431 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006432 };
6433 // clang-format on
6434 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6435 QuicDataWriter writer(packet_length, packet_bytes);
6436 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6437 QUIC_BUG << "Failed to write packet start";
6438 return false;
6439 }
6440
6441 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6442 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006443 if (!AppendIetfConnectionIds(
6444 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6445 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006446 QUIC_BUG << "Failed to write connection IDs";
6447 return false;
6448 }
6449 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6450 // not parse with any known version. The zeroes make sure that packet numbers,
6451 // retry token lengths and payload lengths are parsed as zero, and if the
6452 // zeroes are treated as padding frames, 0xff is known to not parse as a
6453 // valid frame type.
6454 if (!writer.WriteUInt64(0) ||
6455 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6456 QUIC_BUG << "Failed to write 18 bytes";
6457 return false;
6458 }
6459 // Make sure the polite greeting below is padded to a 16-byte boundary to
6460 // make it easier to read in tcpdump.
6461 while (writer.length() % 16 != 0) {
6462 if (!writer.WriteUInt8(0)) {
6463 QUIC_BUG << "Failed to write padding byte";
6464 return false;
6465 }
6466 }
6467 // Add a polite greeting in case a human sees this in tcpdump.
6468 static const char polite_greeting[] =
6469 "This packet only exists to trigger IETF QUIC version negotiation. "
6470 "Please respond with a Version Negotiation packet indicating what "
6471 "versions you support. Thank you and have a nice day.";
6472 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6473 QUIC_BUG << "Failed to write polite greeting";
6474 return false;
6475 }
6476 // Fill the rest of the packet with zeroes.
6477 writer.WritePadding();
6478 DCHECK_EQ(0u, writer.remaining());
6479 return true;
6480}
6481
6482// static
6483bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6484 const char* packet_bytes,
6485 QuicByteCount packet_length,
6486 char* source_connection_id_bytes,
6487 uint8_t* source_connection_id_length_out,
6488 std::string* detailed_error) {
6489 if (detailed_error == nullptr) {
6490 QUIC_BUG << "Invalid error_details";
6491 return false;
6492 }
6493 *detailed_error = "";
6494 if (packet_bytes == nullptr) {
6495 *detailed_error = "Invalid packet_bytes";
6496 return false;
6497 }
6498 if (packet_length < 6) {
6499 *detailed_error = "Invalid packet_length";
6500 return false;
6501 }
6502 if (source_connection_id_bytes == nullptr) {
6503 *detailed_error = "Invalid source_connection_id_bytes";
6504 return false;
6505 }
6506 if (source_connection_id_length_out == nullptr) {
6507 *detailed_error = "Invalid source_connection_id_length_out";
6508 return false;
6509 }
6510 QuicDataReader reader(packet_bytes, packet_length);
6511 uint8_t type_byte = 0;
6512 if (!reader.ReadUInt8(&type_byte)) {
6513 *detailed_error = "Failed to read type byte";
6514 return false;
6515 }
6516 if ((type_byte & 0x80) == 0) {
6517 *detailed_error = "Packet does not have long header";
6518 return false;
6519 }
6520 uint32_t version = 0;
6521 if (!reader.ReadUInt32(&version)) {
6522 *detailed_error = "Failed to read version";
6523 return false;
6524 }
6525 if (version != 0) {
6526 *detailed_error = "Packet is not a version negotiation packet";
6527 return false;
6528 }
dschinazi48ac9192019-07-31 00:07:26 -07006529 const bool use_length_prefix =
6530 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006531 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006532 if (use_length_prefix) {
6533 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6534 *detailed_error = "Failed to read destination connection ID";
6535 return false;
6536 }
6537 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6538 *detailed_error = "Failed to read source connection ID";
6539 return false;
6540 }
6541 } else {
6542 uint8_t expected_server_connection_id_length = 0,
6543 destination_connection_id_length = 0,
6544 source_connection_id_length = 0;
6545 if (!ProcessAndValidateIetfConnectionIdLength(
6546 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6547 /*should_update_expected_server_connection_id_length=*/true,
6548 &expected_server_connection_id_length,
6549 &destination_connection_id_length, &source_connection_id_length,
6550 detailed_error)) {
6551 return false;
6552 }
6553 if (!reader.ReadConnectionId(&destination_connection_id,
6554 destination_connection_id_length)) {
6555 *detailed_error = "Failed to read destination connection ID";
6556 return false;
6557 }
6558 if (!reader.ReadConnectionId(&source_connection_id,
6559 source_connection_id_length)) {
6560 *detailed_error = "Failed to read source connection ID";
6561 return false;
6562 }
dschinazide0f6dc2019-05-15 16:10:11 -07006563 }
dschinazi48ac9192019-07-31 00:07:26 -07006564
6565 if (destination_connection_id.length() != 0) {
6566 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006567 return false;
6568 }
6569
6570 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006571 source_connection_id.length());
6572 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006573
6574 return true;
6575}
6576
fkastenholzb4dade72019-08-05 06:54:20 -07006577// Look for and parse the error code from the "<quic_error_code>:" text that
6578// may be present at the start of the CONNECTION_CLOSE error details string.
6579// This text, inserted by the peer if it's using Google's QUIC implementation,
6580// contains additional error information that narrows down the exact error. If
6581// the string is not found, or is not properly formed, it returns
6582// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
fkastenholz488a4622019-08-26 06:24:46 -07006583void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08006584 std::vector<quiche::QuicheStringPiece> ed =
6585 quiche::QuicheTextUtils::Split(frame->error_details, ':');
fkastenholzb4dade72019-08-05 06:54:20 -07006586 uint64_t extracted_error_code;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006587 if (ed.size() < 2 || !quiche::QuicheTextUtils::IsAllDigits(ed[0]) ||
6588 !quiche::QuicheTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
dschinazidce90b02019-10-14 18:19:54 -07006589 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
bnc77e77b82020-04-05 10:36:49 -07006590 frame->wire_error_code == NO_IETF_QUIC_ERROR) {
6591 frame->quic_error_code = QUIC_NO_ERROR;
dschinazidce90b02019-10-14 18:19:54 -07006592 } else {
bnc77e77b82020-04-05 10:36:49 -07006593 frame->quic_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
dschinazidce90b02019-10-14 18:19:54 -07006594 }
fkastenholz488a4622019-08-26 06:24:46 -07006595 return;
fkastenholzb4dade72019-08-05 06:54:20 -07006596 }
fkastenholz488a4622019-08-26 06:24:46 -07006597 // Return the error code (numeric) and the error details string without the
6598 // error code prefix. Note that Split returns everything up to, but not
6599 // including, the split character, so the length of ed[0] is just the number
6600 // of digits in the error number. In removing the prefix, 1 is added to the
6601 // length to account for the :
dmcardlecf0bfcf2019-12-13 08:08:21 -08006602 quiche::QuicheStringPiece x = quiche::QuicheStringPiece(frame->error_details);
fkastenholz488a4622019-08-26 06:24:46 -07006603 x.remove_prefix(ed[0].length() + 1);
6604 frame->error_details = std::string(x);
bnc77e77b82020-04-05 10:36:49 -07006605 frame->quic_error_code = static_cast<QuicErrorCode>(extracted_error_code);
fkastenholzb4dade72019-08-05 06:54:20 -07006606}
6607
QUICHE teama6ef0a62019-03-07 20:34:33 -05006608#undef ENDPOINT // undef for jumbo builds
6609} // namespace quic