blob: 6e7e58932d72d4f2f551e9ad49bfbf6d67be9c59 [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
469size_t QuicFramer::GetMinAckFrameSize(
470 QuicTransportVersion version,
471 QuicPacketNumberLength largest_observed_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700472 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500473 // The minimal ack frame consists of the following four fields: Largest
474 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
475 // size of each is 1 byte.
476 return kQuicFrameTypeSize + 4;
477 }
478 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
479 kQuicDeltaTimeLargestObservedSize;
480 return min_size + kQuicNumTimestampsSize;
481}
482
483// static
484size_t QuicFramer::GetStopWaitingFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500485 QuicPacketNumberLength packet_number_length) {
486 size_t min_size = kQuicFrameTypeSize + packet_number_length;
487 return min_size;
488}
489
490// static
491size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
492 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700493 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500494 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
495 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700496 kQuicFrameTypeSize +
497 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500498 }
499 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
500 kQuicErrorCodeSize;
501}
502
503// static
fkastenholza037b8b2019-05-07 06:00:05 -0700504size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500505 QuicTransportVersion version,
506 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700507 if (!VersionHasIetfQuicFrames(version)) {
508 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700509 return kQuicFrameTypeSize + kQuicErrorCodeSize +
510 kQuicErrorDetailsLengthSize +
511 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500512 }
fkastenholzb4dade72019-08-05 06:54:20 -0700513
514 // Prepend the extra error information to the string and get the result's
515 // length.
516 const size_t truncated_error_string_size = TruncatedErrorStringSize(
517 GenerateErrorString(frame.error_details, frame.extracted_error_code));
518
fkastenholza037b8b2019-05-07 06:00:05 -0700519 const size_t frame_size =
520 truncated_error_string_size +
521 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholz88d08f42019-09-06 07:38:04 -0700522 kQuicFrameTypeSize +
523 QuicDataWriter::GetVarInt62Len(
524 (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
525 ? frame.transport_error_code
526 : frame.application_error_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700527 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
528 return frame_size;
529 }
fkastenholzb4dade72019-08-05 06:54:20 -0700530 // The Transport close frame has the transport_close_frame_type, so include
531 // its length.
fkastenholza037b8b2019-05-07 06:00:05 -0700532 return frame_size +
533 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500534}
535
536// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500537size_t QuicFramer::GetMinGoAwayFrameSize() {
538 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
539 kQuicMaxStreamIdSize;
540}
541
542// static
543size_t QuicFramer::GetWindowUpdateFrameSize(
544 QuicTransportVersion version,
545 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700546 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500547 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
548 }
549 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
550 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
renjietangd088eab2019-11-21 14:54:41 -0800551 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500552 }
553 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
554 // fields.
renjietangd088eab2019-11-21 14:54:41 -0800555 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500556 QuicDataWriter::GetVarInt62Len(frame.stream_id);
557}
558
559// static
560size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700561 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700562 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500563 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700564 << ", which does not support IETF Frames, and tried to serialize "
565 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500566 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700567 return kQuicFrameTypeSize +
568 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500569}
570
571// static
572size_t QuicFramer::GetStreamsBlockedFrameSize(
573 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700574 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700575 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500576 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700577 << ", which does not support IETF frames, and tried to serialize "
578 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500579 }
580
fkastenholz3c4eabf2019-04-22 07:49:59 -0700581 return kQuicFrameTypeSize +
582 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500583}
584
585// static
586size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
587 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700588 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500589 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
590 }
591 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
592 // return size of IETF QUIC Blocked frame
593 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
594 }
595 // return size of IETF QUIC Stream Blocked frame.
596 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
597 QuicDataWriter::GetVarInt62Len(frame.stream_id);
598}
599
600// static
601size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
602 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700603 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500604}
605
606// static
607size_t QuicFramer::GetPathChallengeFrameSize(
608 const QuicPathChallengeFrame& frame) {
609 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
610}
611
612// static
613size_t QuicFramer::GetPathResponseFrameSize(
614 const QuicPathResponseFrame& frame) {
615 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
616}
617
618// static
619size_t QuicFramer::GetRetransmittableControlFrameSize(
620 QuicTransportVersion version,
621 const QuicFrame& frame) {
622 switch (frame.type) {
623 case PING_FRAME:
624 // Ping has no payload.
625 return kQuicFrameTypeSize;
626 case RST_STREAM_FRAME:
627 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
628 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700629 return GetConnectionCloseFrameSize(version,
630 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500631 case GOAWAY_FRAME:
632 return GetMinGoAwayFrameSize() +
633 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
634 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700635 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500636 // GetWindowUpdateFrameSize figures this out and returns the correct
637 // length.
638 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
639 case BLOCKED_FRAME:
640 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500641 case NEW_CONNECTION_ID_FRAME:
642 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
643 case RETIRE_CONNECTION_ID_FRAME:
644 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
645 case NEW_TOKEN_FRAME:
646 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700647 case MAX_STREAMS_FRAME:
648 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
649 case STREAMS_BLOCKED_FRAME:
650 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500651 case PATH_RESPONSE_FRAME:
652 return GetPathResponseFrameSize(*frame.path_response_frame);
653 case PATH_CHALLENGE_FRAME:
654 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
655 case STOP_SENDING_FRAME:
656 return GetStopSendingFrameSize(*frame.stop_sending_frame);
fayang01062942020-01-22 07:23:23 -0800657 case HANDSHAKE_DONE_FRAME:
658 // HANDSHAKE_DONE has no payload.
659 return kQuicFrameTypeSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500660
661 case STREAM_FRAME:
662 case ACK_FRAME:
663 case STOP_WAITING_FRAME:
664 case MTU_DISCOVERY_FRAME:
665 case PADDING_FRAME:
666 case MESSAGE_FRAME:
667 case CRYPTO_FRAME:
668 case NUM_FRAME_TYPES:
669 DCHECK(false);
670 return 0;
671 }
672
673 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
674 DCHECK(false);
675 return 0;
676}
677
678// static
679size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
680 // Sizes are 1 through 4 bytes.
681 for (int i = 1; i <= 4; ++i) {
682 stream_id >>= 8;
683 if (stream_id == 0) {
684 return i;
685 }
686 }
687 QUIC_BUG << "Failed to determine StreamIDSize.";
688 return 4;
689}
690
691// static
renjietang488201d2019-12-17 13:40:49 -0800692size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500693 // 0 is a special case.
694 if (offset == 0) {
695 return 0;
696 }
697 // 2 through 8 are the remaining sizes.
698 offset >>= 8;
699 for (int i = 2; i <= 8; ++i) {
700 offset >>= 8;
701 if (offset == 0) {
702 return i;
703 }
704 }
705 QUIC_BUG << "Failed to determine StreamOffsetSize.";
706 return 8;
707}
708
709// static
710size_t QuicFramer::GetNewConnectionIdFrameSize(
711 const QuicNewConnectionIdFrame& frame) {
712 return kQuicFrameTypeSize +
713 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700714 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500715 kConnectionIdLengthSize + frame.connection_id.length() +
716 sizeof(frame.stateless_reset_token);
717}
718
719// static
720size_t QuicFramer::GetRetireConnectionIdFrameSize(
721 const QuicRetireConnectionIdFrame& frame) {
722 return kQuicFrameTypeSize +
723 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
724}
725
726// static
727size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
728 return kQuicFrameTypeSize +
729 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
730 frame.token.length();
731}
732
733// TODO(nharper): Change this method to take a ParsedQuicVersion.
734bool QuicFramer::IsSupportedTransportVersion(
735 const QuicTransportVersion version) const {
736 for (ParsedQuicVersion supported_version : supported_versions_) {
737 if (version == supported_version.transport_version) {
738 return true;
739 }
740 }
741 return false;
742}
743
744bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
745 for (const ParsedQuicVersion& supported_version : supported_versions_) {
746 if (version == supported_version) {
747 return true;
748 }
749 }
750 return false;
751}
752
753size_t QuicFramer::GetSerializedFrameLength(
754 const QuicFrame& frame,
755 size_t free_bytes,
756 bool first_frame,
757 bool last_frame,
758 QuicPacketNumberLength packet_number_length) {
759 // Prevent a rare crash reported in b/19458523.
760 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
761 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
762 << free_bytes << " first_frame:" << first_frame
763 << " last_frame:" << last_frame
764 << " seq num length:" << packet_number_length;
765 set_error(QUIC_INTERNAL_ERROR);
766 visitor_->OnError(this);
767 return 0;
768 }
769 if (frame.type == PADDING_FRAME) {
770 if (frame.padding_frame.num_padding_bytes == -1) {
771 // Full padding to the end of the packet.
772 return free_bytes;
773 } else {
774 // Lite padding.
775 return free_bytes <
776 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
777 ? free_bytes
778 : frame.padding_frame.num_padding_bytes;
779 }
780 }
781
782 size_t frame_len =
783 ComputeFrameLength(frame, last_frame, packet_number_length);
784 if (frame_len <= free_bytes) {
785 // Frame fits within packet. Note that acks may be truncated.
786 return frame_len;
787 }
788 // Only truncate the first frame in a packet, so if subsequent ones go
789 // over, stop including more frames.
790 if (!first_frame) {
791 return 0;
792 }
793 bool can_truncate =
794 frame.type == ACK_FRAME &&
795 free_bytes >= GetMinAckFrameSize(version_.transport_version,
796 PACKET_6BYTE_PACKET_NUMBER);
797 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700798 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500799 // Note that we may not use every byte of the writer in this case.
800 QUIC_DLOG(INFO) << ENDPOINT
801 << "Truncating large frame, free bytes: " << free_bytes;
802 return free_bytes;
803 }
804 return 0;
805}
806
807QuicFramer::AckFrameInfo::AckFrameInfo()
808 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
809
810QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
811
812QuicFramer::AckFrameInfo::~AckFrameInfo() {}
813
814bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
815 QuicDataWriter* writer,
816 size_t length_field_offset,
817 EncryptionLevel level) {
818 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
819 !header.version_flag || length_field_offset == 0) {
820 return true;
821 }
822 if (writer->length() < length_field_offset ||
823 writer->length() - length_field_offset <
824 kQuicDefaultLongHeaderLengthLength) {
825 set_detailed_error("Invalid length_field_offset.");
826 QUIC_BUG << "Invalid length_field_offset.";
827 return false;
828 }
829 size_t length_to_write = writer->length() - length_field_offset -
830 kQuicDefaultLongHeaderLengthLength;
831 // Add length of auth tag.
832 length_to_write = GetCiphertextSize(level, length_to_write);
833
834 QuicDataWriter length_writer(writer->length() - length_field_offset,
835 writer->data() + length_field_offset);
836 if (!length_writer.WriteVarInt62(length_to_write,
837 kQuicDefaultLongHeaderLengthLength)) {
838 set_detailed_error("Failed to overwrite long header length.");
839 QUIC_BUG << "Failed to overwrite long header length.";
840 return false;
841 }
842 return true;
843}
844
845size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
846 const QuicFrames& frames,
847 char* buffer,
848 size_t packet_length,
849 EncryptionLevel level) {
dschinaziecad9642019-10-01 10:44:17 -0700850 QUIC_BUG_IF(header.version_flag &&
851 VersionHasIetfInvariantHeader(transport_version()) &&
852 header.long_packet_type == RETRY && !frames.empty())
853 << "IETF RETRY packets cannot contain frames " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500854 QuicDataWriter writer(packet_length, buffer);
855 size_t length_field_offset = 0;
856 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
857 QUIC_BUG << "AppendPacketHeader failed";
858 return 0;
859 }
860
fkastenholz305e1732019-06-18 05:01:22 -0700861 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500862 if (AppendIetfFrames(frames, &writer) == 0) {
863 return 0;
864 }
865 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
866 level)) {
867 return 0;
868 }
869 return writer.length();
870 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500871
872 size_t i = 0;
873 for (const QuicFrame& frame : frames) {
874 // Determine if we should write stream frame length in header.
875 const bool last_frame_in_packet = i == frames.size() - 1;
876 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
877 QUIC_BUG << "AppendTypeByte failed";
878 return 0;
879 }
880
881 switch (frame.type) {
882 case PADDING_FRAME:
883 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
884 QUIC_BUG << "AppendPaddingFrame of "
885 << frame.padding_frame.num_padding_bytes << " failed";
886 return 0;
887 }
888 break;
889 case STREAM_FRAME:
890 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
891 &writer)) {
892 QUIC_BUG << "AppendStreamFrame failed";
893 return 0;
894 }
895 break;
896 case ACK_FRAME:
897 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
898 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
899 return 0;
900 }
901 break;
902 case STOP_WAITING_FRAME:
903 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
904 &writer)) {
905 QUIC_BUG << "AppendStopWaitingFrame failed";
906 return 0;
907 }
908 break;
909 case MTU_DISCOVERY_FRAME:
910 // MTU discovery frames are serialized as ping frames.
911 QUIC_FALLTHROUGH_INTENDED;
912 case PING_FRAME:
913 // Ping has no payload.
914 break;
915 case RST_STREAM_FRAME:
916 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
917 QUIC_BUG << "AppendRstStreamFrame failed";
918 return 0;
919 }
920 break;
921 case CONNECTION_CLOSE_FRAME:
922 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
923 &writer)) {
924 QUIC_BUG << "AppendConnectionCloseFrame failed";
925 return 0;
926 }
927 break;
928 case GOAWAY_FRAME:
929 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
930 QUIC_BUG << "AppendGoAwayFrame failed";
931 return 0;
932 }
933 break;
934 case WINDOW_UPDATE_FRAME:
935 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
936 QUIC_BUG << "AppendWindowUpdateFrame failed";
937 return 0;
938 }
939 break;
940 case BLOCKED_FRAME:
941 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
942 QUIC_BUG << "AppendBlockedFrame failed";
943 return 0;
944 }
945 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500946 case NEW_CONNECTION_ID_FRAME:
947 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700948 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500949 return RaiseError(QUIC_INTERNAL_ERROR);
950 case RETIRE_CONNECTION_ID_FRAME:
951 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700952 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
953 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500954 return RaiseError(QUIC_INTERNAL_ERROR);
955 case NEW_TOKEN_FRAME:
956 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700957 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500958 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700959 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500960 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700961 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500962 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700963 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500964 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700965 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500966 return RaiseError(QUIC_INTERNAL_ERROR);
967 case PATH_RESPONSE_FRAME:
968 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700969 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500970 return RaiseError(QUIC_INTERNAL_ERROR);
971 case PATH_CHALLENGE_FRAME:
972 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700973 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500974 return RaiseError(QUIC_INTERNAL_ERROR);
975 case STOP_SENDING_FRAME:
976 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700977 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500978 return RaiseError(QUIC_INTERNAL_ERROR);
979 case MESSAGE_FRAME:
980 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
981 last_frame_in_packet, &writer)) {
982 QUIC_BUG << "AppendMessageFrame failed";
983 return 0;
984 }
985 break;
986 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -0700987 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500988 set_detailed_error(
989 "Attempt to append CRYPTO frame in version prior to 47.");
990 return RaiseError(QUIC_INTERNAL_ERROR);
991 }
992 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
993 QUIC_BUG << "AppendCryptoFrame failed";
994 return 0;
995 }
996 break;
997 default:
998 RaiseError(QUIC_INVALID_FRAME_DATA);
999 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1000 return 0;
1001 }
1002 ++i;
1003 }
1004
dschinazid1428492019-09-17 23:59:30 -07001005 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) {
1006 return 0;
1007 }
1008
QUICHE teama6ef0a62019-03-07 20:34:33 -05001009 return writer.length();
1010}
1011
1012size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1013 QuicDataWriter* writer) {
1014 size_t i = 0;
1015 for (const QuicFrame& frame : frames) {
1016 // Determine if we should write stream frame length in header.
1017 const bool last_frame_in_packet = i == frames.size() - 1;
1018 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1019 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1020 return 0;
1021 }
1022
1023 switch (frame.type) {
1024 case PADDING_FRAME:
1025 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1026 QUIC_BUG << "AppendPaddingFrame of "
1027 << frame.padding_frame.num_padding_bytes
1028 << " failed: " << detailed_error();
1029 return 0;
1030 }
1031 break;
1032 case STREAM_FRAME:
1033 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1034 writer)) {
1035 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1036 return 0;
1037 }
1038 break;
1039 case ACK_FRAME:
1040 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001041 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1042 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001043 return 0;
1044 }
1045 break;
1046 case STOP_WAITING_FRAME:
1047 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001048 "Attempt to append STOP WAITING frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001049 RaiseError(QUIC_INTERNAL_ERROR);
1050 QUIC_BUG << detailed_error();
1051 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001052 case MTU_DISCOVERY_FRAME:
1053 // MTU discovery frames are serialized as ping frames.
1054 QUIC_FALLTHROUGH_INTENDED;
1055 case PING_FRAME:
1056 // Ping has no payload.
1057 break;
1058 case RST_STREAM_FRAME:
1059 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1060 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1061 return 0;
1062 }
1063 break;
1064 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001065 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1066 writer)) {
1067 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1068 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001069 return 0;
1070 }
1071 break;
1072 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001073 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001074 RaiseError(QUIC_INTERNAL_ERROR);
1075 QUIC_BUG << detailed_error();
1076 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001077 case WINDOW_UPDATE_FRAME:
1078 // Depending on whether there is a stream ID or not, will be either a
1079 // MAX STREAM DATA frame or a MAX DATA frame.
1080 if (frame.window_update_frame->stream_id ==
1081 QuicUtils::GetInvalidStreamId(transport_version())) {
1082 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1083 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1084 return 0;
1085 }
1086 } else {
1087 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1088 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1089 return 0;
1090 }
1091 }
1092 break;
1093 case BLOCKED_FRAME:
1094 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1095 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1096 return 0;
1097 }
1098 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001099 case MAX_STREAMS_FRAME:
1100 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001101 QUIC_BUG << "AppendMaxStreamsFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001102 return 0;
1103 }
1104 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001105 case STREAMS_BLOCKED_FRAME:
1106 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001107 QUIC_BUG << "AppendStreamsBlockedFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001108 return 0;
1109 }
1110 break;
1111 case NEW_CONNECTION_ID_FRAME:
1112 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1113 writer)) {
1114 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1115 return 0;
1116 }
1117 break;
1118 case RETIRE_CONNECTION_ID_FRAME:
1119 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1120 writer)) {
1121 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1122 << detailed_error();
1123 return 0;
1124 }
1125 break;
1126 case NEW_TOKEN_FRAME:
1127 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1128 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1129 return 0;
1130 }
1131 break;
1132 case STOP_SENDING_FRAME:
1133 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1134 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1135 return 0;
1136 }
1137 break;
1138 case PATH_CHALLENGE_FRAME:
1139 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1140 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1141 return 0;
1142 }
1143 break;
1144 case PATH_RESPONSE_FRAME:
1145 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1146 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1147 return 0;
1148 }
1149 break;
1150 case MESSAGE_FRAME:
1151 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1152 last_frame_in_packet, writer)) {
1153 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1154 return 0;
1155 }
1156 break;
1157 case CRYPTO_FRAME:
1158 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1159 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1160 return 0;
1161 }
1162 break;
fayang01062942020-01-22 07:23:23 -08001163 case HANDSHAKE_DONE_FRAME:
1164 // HANDSHAKE_DONE has no payload.
1165 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001166 default:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001167 set_detailed_error("Tried to append unknown frame type.");
dschinazi4a64ab62019-10-01 12:54:00 -07001168 RaiseError(QUIC_INVALID_FRAME_DATA);
1169 QUIC_BUG << "QUIC_INVALID_FRAME_DATA: " << frame.type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001170 return 0;
1171 }
1172 ++i;
1173 }
1174
1175 return writer->length();
1176}
1177
QUICHE teama6ef0a62019-03-07 20:34:33 -05001178// static
1179std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1180 const QuicPublicResetPacket& packet) {
1181 CryptoHandshakeMessage reset;
1182 reset.set_tag(kPRST);
1183 reset.SetValue(kRNON, packet.nonce_proof);
1184 if (packet.client_address.host().address_family() !=
1185 IpAddressFamily::IP_UNSPEC) {
1186 // packet.client_address is non-empty.
1187 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001188 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001189 if (serialized_address.empty()) {
1190 return nullptr;
1191 }
1192 reset.SetStringPiece(kCADR, serialized_address);
1193 }
1194 if (!packet.endpoint_id.empty()) {
1195 reset.SetStringPiece(kEPID, packet.endpoint_id);
1196 }
1197 const QuicData& reset_serialized = reset.GetSerialized();
1198
1199 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1200 reset_serialized.length();
1201 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001202 QuicDataWriter writer(len, buffer.get());
1203
1204 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1205 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1206 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1207 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1208 if (!writer.WriteUInt8(flags)) {
1209 return nullptr;
1210 }
1211
1212 if (!writer.WriteConnectionId(packet.connection_id)) {
1213 return nullptr;
1214 }
1215
1216 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1217 return nullptr;
1218 }
1219
vasilvv0fc587f2019-09-06 13:33:08 -07001220 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001221}
1222
1223// static
1224std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001225 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001226 QuicUint128 stateless_reset_token) {
1227 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1228 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1229 sizeof(stateless_reset_token);
1230 std::unique_ptr<char[]> buffer(new char[len]);
1231 QuicDataWriter writer(len, buffer.get());
1232
1233 uint8_t type = 0;
1234 type |= FLAGS_FIXED_BIT;
1235 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1236 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayang36825da2019-08-21 14:01:27 -07001237 type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001238
1239 // Append type byte.
1240 if (!writer.WriteUInt8(type)) {
1241 return nullptr;
1242 }
1243 // Append random bytes.
1244 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1245 kMinRandomBytesLengthInStatelessReset)) {
1246 return nullptr;
1247 }
1248
1249 // Append stateless reset token.
1250 if (!writer.WriteBytes(&stateless_reset_token,
1251 sizeof(stateless_reset_token))) {
1252 return nullptr;
1253 }
vasilvv0fc587f2019-09-06 13:33:08 -07001254 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001255}
1256
1257// static
1258std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001259 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001260 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001261 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001262 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001263 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001264 ParsedQuicVersionVector wire_versions = versions;
dschinazi5fc6d0c2019-11-26 16:22:05 -08001265 // Add a version reserved for negotiation as suggested by the
1266 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1267 if (wire_versions.empty()) {
1268 // Ensure that version negotiation packets we send have at least two
1269 // versions. This guarantees that, under all circumstances, all QUIC
1270 // packets we send are at least 14 bytes long.
1271 wire_versions = {QuicVersionReservedForNegotiation(),
1272 QuicVersionReservedForNegotiation()};
dschinazi1ac22cc2019-06-25 11:47:50 -07001273 } else {
dschinazi5fc6d0c2019-11-26 16:22:05 -08001274 // This is not uniformely distributed but is acceptable since no security
1275 // depends on this randomness.
1276 size_t version_index = 0;
1277 const bool disable_randomness =
1278 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1279 if (!disable_randomness) {
1280 version_index =
1281 QuicRandom::GetInstance()->RandUint64() % (wire_versions.size() + 1);
dschinazi1ac22cc2019-06-25 11:47:50 -07001282 }
dschinazi5fc6d0c2019-11-26 16:22:05 -08001283 wire_versions.insert(wire_versions.begin() + version_index,
1284 QuicVersionReservedForNegotiation());
dschinazi1ac22cc2019-06-25 11:47:50 -07001285 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001286 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001287 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001288 use_length_prefix, server_connection_id, client_connection_id,
1289 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001290 }
dschinazib417d602019-05-29 13:08:45 -07001291
1292 // The GQUIC encoding does not support encoding client connection IDs.
1293 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001294 // The GQUIC encoding does not support length-prefixed connection IDs.
1295 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001296
dschinazi1ac22cc2019-06-25 11:47:50 -07001297 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001298 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001299 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001300 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001301 QuicDataWriter writer(len, buffer.get());
1302
1303 uint8_t flags = static_cast<uint8_t>(
1304 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
QUICHE teama6ef0a62019-03-07 20:34:33 -05001305 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1306 if (!writer.WriteUInt8(flags)) {
1307 return nullptr;
1308 }
1309
dschinazi8ff74822019-05-28 16:37:20 -07001310 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001311 return nullptr;
1312 }
1313
dschinazi1ac22cc2019-06-25 11:47:50 -07001314 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001315 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001316 return nullptr;
1317 }
1318 }
1319
vasilvv0fc587f2019-09-06 13:33:08 -07001320 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001321}
1322
1323// static
1324std::unique_ptr<QuicEncryptedPacket>
1325QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001326 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001327 QuicConnectionId server_connection_id,
1328 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001329 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001330 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1331 << (use_length_prefix ? "" : "out")
1332 << " length prefix, server_connection_id "
1333 << server_connection_id << " client_connection_id "
1334 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001335 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001336 DCHECK(!versions.empty());
1337 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001338 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001339 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001340 if (use_length_prefix) {
1341 // When using length-prefixed connection IDs, packets carry two lengths
1342 // instead of one.
1343 len += kConnectionIdLengthSize;
1344 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001345 std::unique_ptr<char[]> buffer(new char[len]);
1346 QuicDataWriter writer(len, buffer.get());
1347
1348 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001349 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001350 if (!writer.WriteUInt8(type)) {
1351 return nullptr;
1352 }
1353
1354 if (!writer.WriteUInt32(0)) {
1355 return nullptr;
1356 }
1357
dschinazi48ac9192019-07-31 00:07:26 -07001358 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1359 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001360 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001361 }
1362
1363 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001364 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001365 return nullptr;
1366 }
1367 }
1368
vasilvv0fc587f2019-09-06 13:33:08 -07001369 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001370}
1371
1372bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1373 QuicDataReader reader(packet.data(), packet.length());
1374
1375 bool packet_has_ietf_packet_header = false;
1376 if (infer_packet_header_type_from_version_) {
1377 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001378 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001379 } else if (!reader.IsDoneReading()) {
1380 uint8_t type = reader.PeekByte();
1381 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1382 }
1383 if (packet_has_ietf_packet_header) {
1384 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1385 }
1386
1387 visitor_->OnPacket();
1388
1389 QuicPacketHeader header;
1390 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1391 DCHECK_NE("", detailed_error_);
1392 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1393 << detailed_error_;
1394 DCHECK_NE("", detailed_error_);
1395 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1396 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1397 }
1398
1399 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1400 // The visitor suppresses further processing of the packet.
1401 return true;
1402 }
1403
dschinazie0df3f72019-05-06 16:37:51 -07001404 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001405 if (perspective_ == Perspective::IS_CLIENT) {
1406 QUIC_DVLOG(1) << "Client received version negotiation packet";
1407 return ProcessVersionNegotiationPacket(&reader, header);
1408 } else {
1409 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1410 set_detailed_error("Server received version negotiation packet.");
1411 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1412 }
dschinazie0df3f72019-05-06 16:37:51 -07001413 }
1414
1415 if (header.version_flag && header.version != version_) {
1416 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001417 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001418 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1419 return true;
1420 }
1421 } else {
1422 // A client received a packet of a different version but that packet is
1423 // not a version negotiation packet. It is therefore invalid and dropped.
1424 QUIC_DLOG(ERROR) << "Client received unexpected version "
1425 << ParsedQuicVersionToString(header.version)
1426 << " instead of " << ParsedQuicVersionToString(version_);
1427 set_detailed_error("Client received unexpected version.");
1428 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001429 }
1430 }
1431
1432 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001433 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001434 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001435 } else if (header.reset_flag) {
1436 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001437 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001438 // The optimized decryption algorithm implementations run faster when
1439 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001440 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001441 if (packet_has_ietf_packet_header) {
1442 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001443 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001444 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001445 rv = ProcessDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001446 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001447 }
1448 } else {
1449 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1450 if (packet_has_ietf_packet_header) {
1451 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1452 packet.length());
1453 } else {
1454 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1455 packet.length());
1456 }
1457 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001458 << "than kMaxIncomingPacketSize. packet size:"
1459 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001460 }
1461 return rv;
1462}
1463
1464bool QuicFramer::ProcessVersionNegotiationPacket(
1465 QuicDataReader* reader,
1466 const QuicPacketHeader& header) {
1467 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1468
QUICHE team2252b702019-05-14 23:55:14 -04001469 QuicVersionNegotiationPacket packet(
1470 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001471 // Try reading at least once to raise error if the packet is invalid.
1472 do {
1473 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001474 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001475 set_detailed_error("Unable to read supported version in negotiation.");
1476 RecordDroppedPacketReason(
1477 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1478 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1479 }
nharper4fd11052019-06-04 14:23:22 -07001480 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1481 if (parsed_version != UnsupportedQuicVersion()) {
1482 packet.versions.push_back(parsed_version);
1483 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001484 } while (!reader->IsDoneReading());
1485
dschinazi5a354c92019-05-09 12:18:53 -07001486 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1487 << ParsedQuicVersionVectorToString(packet.versions);
1488
QUICHE teama6ef0a62019-03-07 20:34:33 -05001489 visitor_->OnVersionNegotiationPacket(packet);
1490 return true;
1491}
1492
dschinazi244f6dc2019-05-06 15:45:16 -07001493bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1494 const QuicPacketHeader& header) {
1495 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1496
dschinazi278efae2020-01-28 17:03:09 -08001497 if (version_.HasRetryIntegrityTag()) {
1498 DCHECK(version_.HasLengthPrefixedConnectionIds()) << version_;
1499 const size_t bytes_remaining = reader->BytesRemaining();
1500 if (bytes_remaining <= kRetryIntegrityTagLength) {
1501 set_detailed_error("Retry packet too short to parse integrity tag.");
1502 return false;
1503 }
1504 const size_t retry_token_length =
1505 bytes_remaining - kRetryIntegrityTagLength;
1506 DCHECK_GT(retry_token_length, 0u);
1507 quiche::QuicheStringPiece retry_token;
1508 if (!reader->ReadStringPiece(&retry_token, retry_token_length)) {
1509 set_detailed_error("Failed to read retry token.");
1510 return false;
1511 }
1512 quiche::QuicheStringPiece retry_without_tag =
1513 reader->PreviouslyReadPayload();
1514 quiche::QuicheStringPiece integrity_tag = reader->ReadRemainingPayload();
1515 DCHECK_EQ(integrity_tag.length(), kRetryIntegrityTagLength);
1516 visitor_->OnRetryPacket(EmptyQuicConnectionId(),
1517 header.source_connection_id, retry_token,
1518 integrity_tag, retry_without_tag);
1519 return true;
1520 }
1521
dschinazi244f6dc2019-05-06 15:45:16 -07001522 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001523 if (version_.HasLengthPrefixedConnectionIds()) {
1524 // Parse Original Destination Connection ID.
1525 if (!reader->ReadLengthPrefixedConnectionId(
1526 &original_destination_connection_id)) {
1527 set_detailed_error("Unable to read Original Destination ConnectionId.");
1528 return false;
1529 }
1530 } else {
1531 // Parse Original Destination Connection ID Length.
1532 uint8_t odcil = header.type_byte & 0xf;
1533 if (odcil != 0) {
1534 odcil += kConnectionIdLengthAdjustment;
1535 }
1536
1537 // Parse Original Destination Connection ID.
1538 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1539 set_detailed_error("Unable to read Original Destination ConnectionId.");
1540 return false;
1541 }
dschinazi244f6dc2019-05-06 15:45:16 -07001542 }
1543
dschinazib953d022019-08-01 18:05:58 -07001544 if (!QuicUtils::IsConnectionIdValidForVersion(
1545 original_destination_connection_id, transport_version())) {
1546 set_detailed_error(
1547 "Received Original Destination ConnectionId with invalid length.");
1548 return false;
1549 }
1550
dmcardlecf0bfcf2019-12-13 08:08:21 -08001551 quiche::QuicheStringPiece retry_token = reader->ReadRemainingPayload();
dschinazi244f6dc2019-05-06 15:45:16 -07001552 visitor_->OnRetryPacket(original_destination_connection_id,
dschinazi278efae2020-01-28 17:03:09 -08001553 header.source_connection_id, retry_token,
1554 /*retry_integrity_tag=*/quiche::QuicheStringPiece(),
1555 /*retry_without_tag=*/quiche::QuicheStringPiece());
dschinazi244f6dc2019-05-06 15:45:16 -07001556 return true;
1557}
1558
QUICHE teama6ef0a62019-03-07 20:34:33 -05001559// Seeks the current packet to check for a coalesced packet at the end.
1560// If the IETF length field only spans part of the outer packet,
1561// then there is a coalesced packet after this one.
1562void QuicFramer::MaybeProcessCoalescedPacket(
1563 const QuicDataReader& encrypted_reader,
1564 uint64_t remaining_bytes_length,
1565 const QuicPacketHeader& header) {
1566 if (header.remaining_packet_length >= remaining_bytes_length) {
1567 // There is no coalesced packet.
1568 return;
1569 }
1570
dmcardlecf0bfcf2019-12-13 08:08:21 -08001571 quiche::QuicheStringPiece remaining_data =
1572 encrypted_reader.PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001573 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1574
1575 const char* coalesced_data =
1576 remaining_data.data() + header.remaining_packet_length;
1577 uint64_t coalesced_data_length =
1578 remaining_bytes_length - header.remaining_packet_length;
1579 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1580
1581 QuicPacketHeader coalesced_header;
1582 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
fayangd1160ff2020-02-26 11:57:09 -08001583 // Some implementations pad their INITIAL packets by sending random invalid
1584 // data after the INITIAL, and that is allowed by the specification. If we
1585 // fail to parse a subsequent coalesced packet, simply ignore it.
1586 QUIC_DLOG(INFO) << ENDPOINT
1587 << "Failed to parse received coalesced header of length "
1588 << coalesced_data_length
1589 << " with error: " << detailed_error_ << ": "
1590 << quiche::QuicheTextUtils::HexEncode(coalesced_data,
1591 coalesced_data_length)
1592 << " previous header was " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001593 return;
1594 }
1595
fayangd1160ff2020-02-26 11:57:09 -08001596 if (GetQuicReloadableFlag(quic_minimum_validation_of_coalesced_packets)) {
1597 QUIC_RELOADABLE_FLAG_COUNT(quic_minimum_validation_of_coalesced_packets);
1598 if (coalesced_header.destination_connection_id !=
1599 header.destination_connection_id) {
1600 // Drop coalesced packets with mismatched connection IDs.
1601 QUIC_DLOG(INFO) << ENDPOINT << "Received mismatched coalesced header "
1602 << coalesced_header << " previous header was " << header;
1603 QUIC_CODE_COUNT(
1604 quic_received_coalesced_packets_with_mismatched_connection_id);
1605 return;
1606 }
1607 } else {
1608 if (coalesced_header.destination_connection_id !=
1609 header.destination_connection_id ||
1610 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1611 coalesced_header.version != header.version)) {
1612 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1613 << coalesced_header << " previous header was " << header;
1614 return;
1615 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001616 }
1617
1618 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1619 /*owns_buffer=*/false);
1620 visitor_->OnCoalescedPacket(coalesced_packet);
1621}
1622
1623bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1624 QuicPacketHeader* header) {
1625 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1626 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1627 (header->long_packet_type != INITIAL &&
1628 header->long_packet_type != HANDSHAKE &&
1629 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1630 return true;
1631 }
1632 header->length_length = encrypted_reader->PeekVarInt62Length();
1633 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1634 set_detailed_error("Unable to read long header payload length.");
1635 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1636 }
1637 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1638 if (header->remaining_packet_length > remaining_bytes_length) {
1639 set_detailed_error("Long header payload length longer than packet.");
1640 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1641 }
1642
1643 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1644 *header);
1645
1646 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1647 set_detailed_error("Length TruncateRemaining failed.");
1648 QUIC_BUG << "Length TruncateRemaining failed.";
1649 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1650 }
1651 return true;
1652}
1653
1654bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1655 QuicPacketHeader* header,
1656 const QuicEncryptedPacket& packet,
1657 char* decrypted_buffer,
1658 size_t buffer_length) {
1659 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1660 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001661 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1662 header->remaining_packet_length = 0;
1663 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1664 perspective_ == Perspective::IS_CLIENT) {
1665 // Peek possible stateless reset token. Will only be used on decryption
1666 // failure.
dmcardlecf0bfcf2019-12-13 08:08:21 -08001667 quiche::QuicheStringPiece remaining =
1668 encrypted_reader->PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001669 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1670 header->has_possible_stateless_reset_token = true;
1671 memcpy(&header->possible_stateless_reset_token,
1672 &remaining.data()[remaining.length() -
1673 sizeof(header->possible_stateless_reset_token)],
1674 sizeof(header->possible_stateless_reset_token));
1675 }
1676 }
1677
QUICHE teama6ef0a62019-03-07 20:34:33 -05001678 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1679 return false;
1680 }
1681
dmcardlecf0bfcf2019-12-13 08:08:21 -08001682 quiche::QuicheStringPiece associated_data;
nharper55fa6132019-05-07 19:37:21 -07001683 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001684 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1685 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001686 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1687 header->long_packet_type == INITIAL ||
1688 header->long_packet_type == HANDSHAKE ||
1689 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001690 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001691 QuicPacketNumber base_packet_number;
1692 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001693 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1694 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1695 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1696 }
1697 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001698 } else {
1699 base_packet_number = largest_packet_number_;
1700 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001701 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001702 bool hp_removal_failed = false;
1703 if (version_.HasHeaderProtection()) {
1704 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1705 &full_packet_number, &ad_storage)) {
1706 hp_removal_failed = true;
1707 }
dmcardlecf0bfcf2019-12-13 08:08:21 -08001708 associated_data =
1709 quiche::QuicheStringPiece(ad_storage.data(), ad_storage.size());
nharper55fa6132019-05-07 19:37:21 -07001710 } else if (!ProcessAndCalculatePacketNumber(
1711 encrypted_reader, header->packet_number_length,
1712 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001713 set_detailed_error("Unable to read packet number.");
1714 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1715 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1716 }
1717
nharper55fa6132019-05-07 19:37:21 -07001718 if (hp_removal_failed ||
dschinazi40f0b3d2020-02-19 17:54:05 -08001719 !IsValidFullPacketNumber(full_packet_number, version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001720 if (IsIetfStatelessResetPacket(*header)) {
1721 // This is a stateless reset packet.
1722 QuicIetfStatelessResetPacket packet(
1723 *header, header->possible_stateless_reset_token);
1724 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1725 return true;
1726 }
nharper55fa6132019-05-07 19:37:21 -07001727 if (hp_removal_failed) {
wub13d75452019-11-05 07:24:56 -08001728 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1729 const bool has_decryption_key = decrypter_[decryption_level] != nullptr;
1730 visitor_->OnUndecryptablePacket(
1731 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1732 decryption_level, has_decryption_key);
nharper55fa6132019-05-07 19:37:21 -07001733 set_detailed_error("Unable to decrypt header protection.");
1734 return RaiseError(QUIC_DECRYPTION_FAILURE);
1735 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001736 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1737 set_detailed_error("packet numbers cannot be 0.");
1738 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1739 }
1740 header->packet_number = QuicPacketNumber(full_packet_number);
1741 }
1742
1743 // A nonce should only present in SHLO from the server to the client when
1744 // using QUIC crypto.
1745 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1746 header->long_packet_type == ZERO_RTT_PROTECTED &&
1747 perspective_ == Perspective::IS_CLIENT &&
1748 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1749 if (!encrypted_reader->ReadBytes(
1750 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1751 last_nonce_.size())) {
1752 set_detailed_error("Unable to read nonce.");
1753 RecordDroppedPacketReason(
1754 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1755 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1756 }
1757
1758 header->nonce = &last_nonce_;
1759 } else {
1760 header->nonce = nullptr;
1761 }
1762
1763 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1764 set_detailed_error(
1765 "Visitor asked to stop processing of unauthenticated header.");
1766 return false;
1767 }
1768
dmcardlecf0bfcf2019-12-13 08:08:21 -08001769 quiche::QuicheStringPiece encrypted =
1770 encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001771 if (!version_.HasHeaderProtection()) {
1772 associated_data = GetAssociatedDataFromEncryptedPacket(
1773 version_.transport_version, packet,
1774 GetIncludedDestinationConnectionIdLength(*header),
1775 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1776 header->nonce != nullptr, header->packet_number_length,
1777 header->retry_token_length_length, header->retry_token.length(),
1778 header->length_length);
1779 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001780
1781 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001782 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001783 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001784 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001785 if (IsIetfStatelessResetPacket(*header)) {
1786 // This is a stateless reset packet.
1787 QuicIetfStatelessResetPacket packet(
1788 *header, header->possible_stateless_reset_token);
1789 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1790 return true;
1791 }
wub13d75452019-11-05 07:24:56 -08001792 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1793 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1794 decrypter_[decryption_level] != nullptr;
1795 visitor_->OnUndecryptablePacket(
1796 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1797 has_decryption_key);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001798 set_detailed_error("Unable to decrypt payload.");
1799 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1800 return RaiseError(QUIC_DECRYPTION_FAILURE);
1801 }
1802 QuicDataReader reader(decrypted_buffer, decrypted_length);
1803
1804 // Update the largest packet number after we have decrypted the packet
1805 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001806 if (supports_multiple_packet_number_spaces_) {
1807 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1808 decrypted_level)]
1809 .UpdateMax(header->packet_number);
1810 } else {
1811 largest_packet_number_.UpdateMax(header->packet_number);
1812 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001813
1814 if (!visitor_->OnPacketHeader(*header)) {
1815 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1816 // The visitor suppresses further processing of the packet.
1817 return true;
1818 }
1819
dschinazie8d7fa72019-04-05 14:44:40 -07001820 if (packet.length() > kMaxIncomingPacketSize) {
1821 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001822 return RaiseError(QUIC_PACKET_TOO_LARGE);
1823 }
1824
1825 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001826 if (VersionHasIetfQuicFrames(version_.transport_version)) {
fkastenholza3660102019-08-28 05:19:24 -07001827 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001828 if (!ProcessIetfFrameData(&reader, *header)) {
fkastenholza3660102019-08-28 05:19:24 -07001829 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001830 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1831 DCHECK_NE("", detailed_error_);
1832 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1833 << detailed_error_;
1834 return false;
1835 }
fkastenholza3660102019-08-28 05:19:24 -07001836 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001837 } else {
1838 if (!ProcessFrameData(&reader, *header)) {
1839 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1840 DCHECK_NE("", detailed_error_);
1841 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1842 << detailed_error_;
1843 return false;
1844 }
1845 }
1846
1847 visitor_->OnPacketComplete();
1848 return true;
1849}
1850
1851bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1852 QuicPacketHeader* header,
1853 const QuicEncryptedPacket& packet,
1854 char* decrypted_buffer,
1855 size_t buffer_length) {
1856 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1857 DCHECK_NE("", detailed_error_);
1858 QUIC_DVLOG(1)
1859 << ENDPOINT
1860 << "Unable to process packet header. Stopping parsing. Error: "
1861 << detailed_error_;
1862 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1863 return false;
1864 }
1865
dmcardlecf0bfcf2019-12-13 08:08:21 -08001866 quiche::QuicheStringPiece encrypted =
1867 encrypted_reader->ReadRemainingPayload();
1868 quiche::QuicheStringPiece associated_data =
1869 GetAssociatedDataFromEncryptedPacket(
1870 version_.transport_version, packet,
1871 GetIncludedDestinationConnectionIdLength(*header),
1872 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1873 header->nonce != nullptr, header->packet_number_length,
1874 header->retry_token_length_length, header->retry_token.length(),
1875 header->length_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001876
1877 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001878 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001879 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001880 buffer_length, &decrypted_length, &decrypted_level)) {
wub13d75452019-11-05 07:24:56 -08001881 const EncryptionLevel decryption_level = decrypter_level_;
1882 // This version uses trial decryption so we always report to our visitor
1883 // that we are not certain we have the correct decryption key.
1884 const bool has_decryption_key = false;
1885 visitor_->OnUndecryptablePacket(
1886 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1887 has_decryption_key);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001888 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1889 set_detailed_error("Unable to decrypt payload.");
1890 return RaiseError(QUIC_DECRYPTION_FAILURE);
1891 }
1892
1893 QuicDataReader reader(decrypted_buffer, decrypted_length);
1894
1895 // Update the largest packet number after we have decrypted the packet
1896 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001897 if (supports_multiple_packet_number_spaces_) {
1898 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1899 decrypted_level)]
1900 .UpdateMax(header->packet_number);
1901 } else {
1902 largest_packet_number_.UpdateMax(header->packet_number);
1903 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001904
1905 if (!visitor_->OnPacketHeader(*header)) {
1906 // The visitor suppresses further processing of the packet.
1907 return true;
1908 }
1909
dschinazie8d7fa72019-04-05 14:44:40 -07001910 if (packet.length() > kMaxIncomingPacketSize) {
1911 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001912 return RaiseError(QUIC_PACKET_TOO_LARGE);
1913 }
1914
1915 // Handle the payload.
1916 if (!ProcessFrameData(&reader, *header)) {
1917 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1918 DCHECK_NE("", detailed_error_);
1919 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1920 << detailed_error_;
1921 return false;
1922 }
1923
1924 visitor_->OnPacketComplete();
1925 return true;
1926}
1927
1928bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1929 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001930 QuicPublicResetPacket packet(
1931 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001932
1933 std::unique_ptr<CryptoHandshakeMessage> reset(
1934 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
wub07a2b072019-10-24 11:23:20 -07001935 if (!reset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001936 set_detailed_error("Unable to read reset message.");
1937 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1938 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1939 }
1940 if (reset->tag() != kPRST) {
1941 set_detailed_error("Incorrect message tag.");
1942 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1943 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1944 }
1945
1946 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
1947 set_detailed_error("Unable to read nonce proof.");
1948 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1949 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1950 }
1951 // TODO(satyamshekhar): validate nonce to protect against DoS.
1952
dmcardlecf0bfcf2019-12-13 08:08:21 -08001953 quiche::QuicheStringPiece address;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001954 if (reset->GetStringPiece(kCADR, &address)) {
1955 QuicSocketAddressCoder address_coder;
1956 if (address_coder.Decode(address.data(), address.length())) {
1957 packet.client_address =
1958 QuicSocketAddress(address_coder.ip(), address_coder.port());
1959 }
1960 }
1961
dmcardlecf0bfcf2019-12-13 08:08:21 -08001962 quiche::QuicheStringPiece endpoint_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001963 if (perspective_ == Perspective::IS_CLIENT &&
1964 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07001965 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001966 packet.endpoint_id += '\0';
1967 }
1968
1969 visitor_->OnPublicResetPacket(packet);
1970 return true;
1971}
1972
1973bool QuicFramer::IsIetfStatelessResetPacket(
1974 const QuicPacketHeader& header) const {
1975 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
1976 perspective_ != Perspective::IS_CLIENT)
1977 << "has_possible_stateless_reset_token can only be true at client side.";
1978 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
1979 header.has_possible_stateless_reset_token &&
1980 visitor_->IsValidStatelessResetToken(
1981 header.possible_stateless_reset_token);
1982}
1983
1984bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
1985 return encrypter_[level] != nullptr;
1986}
1987
1988bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
1989 QuicDataWriter* writer,
1990 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07001991 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001992 return AppendIetfPacketHeader(header, writer, length_field_offset);
1993 }
1994 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
1995 uint8_t public_flags = 0;
1996 if (header.reset_flag) {
1997 public_flags |= PACKET_PUBLIC_FLAGS_RST;
1998 }
1999 if (header.version_flag) {
2000 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2001 }
2002
2003 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2004 << kPublicHeaderSequenceNumberShift;
2005
2006 if (header.nonce != nullptr) {
2007 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2008 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2009 }
QUICHE team2252b702019-05-14 23:55:14 -04002010
dschinazi7b9278c2019-05-20 07:36:21 -07002011 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002012 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002013 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002014 GetServerConnectionIdIncludedAsSender(header, perspective_);
2015 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002016 GetClientConnectionIdIncludedAsSender(header, perspective_))
2017 << ENDPOINT << ParsedQuicVersionToString(version_)
2018 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002019
dschinazi7b9278c2019-05-20 07:36:21 -07002020 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002021 case CONNECTION_ID_ABSENT:
2022 if (!writer->WriteUInt8(public_flags |
2023 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2024 return false;
2025 }
2026 break;
2027 case CONNECTION_ID_PRESENT:
2028 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002029 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002030 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002031 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002032 << QuicVersionToString(transport_version());
2033
2034 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2035 if (perspective_ == Perspective::IS_CLIENT) {
2036 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2037 }
2038 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002039 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002040 return false;
2041 }
2042 break;
2043 }
dschinazi7b9278c2019-05-20 07:36:21 -07002044 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002045
2046 if (header.version_flag) {
2047 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2048 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002049 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002050 return false;
2051 }
2052
2053 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2054 << QuicVersionLabelToString(version_label) << "'";
2055 }
2056
2057 if (header.nonce != nullptr &&
2058 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2059 return false;
2060 }
2061
2062 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2063 writer)) {
2064 return false;
2065 }
2066
2067 return true;
2068}
2069
2070bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2071 QuicDataWriter* writer) {
2072 uint8_t type = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002073 if (header.version_flag) {
2074 type = static_cast<uint8_t>(
fayang36825da2019-08-21 14:01:27 -07002075 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2076 LongHeaderTypeToOnWireValue(header.long_packet_type) |
2077 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002078 } else {
fayang36825da2019-08-21 14:01:27 -07002079 type = static_cast<uint8_t>(
2080 FLAGS_FIXED_BIT |
2081 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002082 }
2083 return writer->WriteUInt8(type);
2084}
2085
2086bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2087 QuicDataWriter* writer,
2088 size_t* length_field_offset) {
2089 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002090 QuicConnectionId server_connection_id =
2091 GetServerConnectionIdAsSender(header, perspective_);
2092 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2093 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002094 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002095 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002096 << QuicVersionToString(transport_version());
2097 if (!AppendIetfHeaderTypeByte(header, writer)) {
2098 return false;
2099 }
2100
2101 if (header.version_flag) {
dschinaziecad9642019-10-01 10:44:17 -07002102 DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type)
2103 << "QuicFramer::AppendIetfPacketHeader does not support sending "
2104 "version negotiation packets, use "
2105 "QuicFramer::BuildVersionNegotiationPacket instead "
2106 << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002107 // Append version for long header.
2108 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002109 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002110 return false;
2111 }
2112 }
2113
2114 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002115 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002116 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002117 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2118 ? header.destination_connection_id
2119 : EmptyQuicConnectionId(),
2120 header.source_connection_id_included != CONNECTION_ID_ABSENT
2121 ? header.source_connection_id
2122 : EmptyQuicConnectionId(),
2123 writer)) {
2124 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002125 }
dschinazi1f485a12019-05-13 11:57:01 -07002126
dschinazi7b9278c2019-05-20 07:36:21 -07002127 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002128 if (version_.SupportsClientConnectionIds()) {
2129 last_serialized_client_connection_id_ =
2130 GetClientConnectionIdAsSender(header, perspective_);
2131 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002132
dschinaziecad9642019-10-01 10:44:17 -07002133 // TODO(b/141924462) Remove this QUIC_BUG once we do support sending RETRY.
2134 QUIC_BUG_IF(header.version_flag && header.long_packet_type == RETRY)
2135 << "Sending IETF RETRY packets is not currently supported " << header;
2136
QUICHE teama6ef0a62019-03-07 20:34:33 -05002137 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2138 header.version_flag) {
2139 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002140 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2141 header.retry_token_length_length)
2142 << ENDPOINT << ParsedQuicVersionToString(version_)
2143 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002144 // Write retry token length.
2145 if (!writer->WriteVarInt62(header.retry_token.length(),
2146 header.retry_token_length_length)) {
2147 return false;
2148 }
2149 // Write retry token.
2150 if (!header.retry_token.empty() &&
2151 !writer->WriteStringPiece(header.retry_token)) {
2152 return false;
2153 }
2154 }
2155 if (length_field_offset != nullptr) {
2156 *length_field_offset = writer->length();
2157 }
2158 // Add fake length to reserve two bytes to add length in later.
2159 writer->WriteVarInt62(256);
2160 } else if (length_field_offset != nullptr) {
2161 *length_field_offset = 0;
2162 }
2163
2164 // Append packet number.
2165 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2166 writer)) {
2167 return false;
2168 }
nharper55fa6132019-05-07 19:37:21 -07002169 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002170
2171 if (!header.version_flag) {
2172 return true;
2173 }
2174
2175 if (header.nonce != nullptr) {
2176 DCHECK(header.version_flag);
2177 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2178 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2179 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2180 return false;
2181 }
2182 }
2183
2184 return true;
2185}
2186
2187const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2188 uint32_t time_delta_us) {
2189 // The new time_delta might have wrapped to the next epoch, or it
2190 // might have reverse wrapped to the previous epoch, or it might
2191 // remain in the same epoch. Select the time closest to the previous
2192 // time.
2193 //
2194 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2195 // microseconds.
2196 const uint64_t epoch_delta = UINT64_C(1) << 32;
2197 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2198 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2199 uint64_t prev_epoch = epoch - epoch_delta;
2200 uint64_t next_epoch = epoch + epoch_delta;
2201
2202 uint64_t time = ClosestTo(
2203 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2204 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2205 next_epoch + time_delta_us));
2206
2207 return QuicTime::Delta::FromMicroseconds(time);
2208}
2209
2210uint64_t QuicFramer::CalculatePacketNumberFromWire(
2211 QuicPacketNumberLength packet_number_length,
2212 QuicPacketNumber base_packet_number,
2213 uint64_t packet_number) const {
2214 // The new packet number might have wrapped to the next epoch, or
2215 // it might have reverse wrapped to the previous epoch, or it might
2216 // remain in the same epoch. Select the packet number closest to the
2217 // next expected packet number, the previous packet number plus 1.
2218
2219 // epoch_delta is the delta between epochs the packet number was serialized
2220 // with, so the correct value is likely the same epoch as the last sequence
2221 // number or an adjacent epoch.
2222 if (!base_packet_number.IsInitialized()) {
2223 return packet_number;
2224 }
2225 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2226 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2227 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2228 uint64_t prev_epoch = epoch - epoch_delta;
2229 uint64_t next_epoch = epoch + epoch_delta;
2230
2231 return ClosestTo(next_packet_number, epoch + packet_number,
2232 ClosestTo(next_packet_number, prev_epoch + packet_number,
2233 next_epoch + packet_number));
2234}
2235
2236bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2237 bool packet_has_ietf_packet_header,
2238 QuicPacketHeader* header) {
2239 if (packet_has_ietf_packet_header) {
2240 return ProcessIetfPacketHeader(reader, header);
2241 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002242 uint8_t public_flags;
2243 if (!reader->ReadBytes(&public_flags, 1)) {
2244 set_detailed_error("Unable to read public flags.");
2245 return false;
2246 }
2247
2248 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2249 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2250
2251 if (validate_flags_ && !header->version_flag &&
2252 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2253 set_detailed_error("Illegal public flags value.");
2254 return false;
2255 }
2256
2257 if (header->reset_flag && header->version_flag) {
2258 set_detailed_error("Got version flag in reset packet");
2259 return false;
2260 }
2261
QUICHE team2252b702019-05-14 23:55:14 -04002262 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2263 QuicConnectionIdIncluded* header_connection_id_included =
2264 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002265 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002266 header_connection_id = &header->source_connection_id;
2267 header_connection_id_included = &header->source_connection_id_included;
2268 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002269 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2270 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002271 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002272 kQuicDefaultConnectionIdLength)) {
2273 set_detailed_error("Unable to read ConnectionId.");
2274 return false;
2275 }
QUICHE team2252b702019-05-14 23:55:14 -04002276 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002277 break;
2278 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002279 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002280 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002281 break;
2282 }
2283
2284 header->packet_number_length = ReadSequenceNumberLength(
2285 public_flags >> kPublicHeaderSequenceNumberShift);
2286
2287 // Read the version only if the packet is from the client.
2288 // version flag from the server means version negotiation packet.
2289 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2290 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002291 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002292 set_detailed_error("Unable to read protocol version.");
2293 return false;
2294 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002295 // If the version from the new packet is the same as the version of this
2296 // framer, then the public flags should be set to something we understand.
2297 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002298 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2299 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2300 set_detailed_error("Illegal public flags value.");
2301 return false;
2302 }
2303 header->version = version;
2304 }
2305
2306 // A nonce should only be present in packets from the server to the client,
2307 // which are neither version negotiation nor public reset packets.
2308 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2309 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2310 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2311 // The nonce flag from a client is ignored and is assumed to be an older
2312 // client indicating an eight-byte connection ID.
2313 perspective_ == Perspective::IS_CLIENT) {
2314 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2315 last_nonce_.size())) {
2316 set_detailed_error("Unable to read nonce.");
2317 return false;
2318 }
2319 header->nonce = &last_nonce_;
2320 } else {
2321 header->nonce = nullptr;
2322 }
2323
2324 return true;
2325}
2326
2327// static
2328QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05002329 QuicPacketNumber packet_number) {
2330 DCHECK(packet_number.IsInitialized());
2331 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2332 return PACKET_1BYTE_PACKET_NUMBER;
2333 } else if (packet_number <
2334 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2335 return PACKET_2BYTE_PACKET_NUMBER;
2336 } else if (packet_number <
2337 QuicPacketNumber(UINT64_C(1)
2338 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2339 return PACKET_4BYTE_PACKET_NUMBER;
2340 } else {
2341 return PACKET_6BYTE_PACKET_NUMBER;
2342 }
2343}
2344
2345// static
2346uint8_t QuicFramer::GetPacketNumberFlags(
2347 QuicPacketNumberLength packet_number_length) {
2348 switch (packet_number_length) {
2349 case PACKET_1BYTE_PACKET_NUMBER:
2350 return PACKET_FLAGS_1BYTE_PACKET;
2351 case PACKET_2BYTE_PACKET_NUMBER:
2352 return PACKET_FLAGS_2BYTE_PACKET;
2353 case PACKET_4BYTE_PACKET_NUMBER:
2354 return PACKET_FLAGS_4BYTE_PACKET;
2355 case PACKET_6BYTE_PACKET_NUMBER:
2356 case PACKET_8BYTE_PACKET_NUMBER:
2357 return PACKET_FLAGS_8BYTE_PACKET;
2358 default:
2359 QUIC_BUG << "Unreachable case statement.";
2360 return PACKET_FLAGS_8BYTE_PACKET;
2361 }
2362}
2363
2364// static
2365QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2366 const QuicAckFrame& frame) {
2367 AckFrameInfo new_ack_info;
2368 if (frame.packets.Empty()) {
2369 return new_ack_info;
2370 }
2371 // The first block is the last interval. It isn't encoded with the gap-length
2372 // encoding, so skip it.
2373 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2374 auto itr = frame.packets.rbegin();
2375 QuicPacketNumber previous_start = itr->min();
wub13d75452019-11-05 07:24:56 -08002376 new_ack_info.max_block_length = itr->Length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002377 ++itr;
2378
2379 // Don't do any more work after getting information for 256 ACK blocks; any
2380 // more can't be encoded anyway.
2381 for (; itr != frame.packets.rend() &&
2382 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2383 previous_start = itr->min(), ++itr) {
2384 const auto& interval = *itr;
2385 const QuicPacketCount total_gap = previous_start - interval.max();
2386 new_ack_info.num_ack_blocks +=
2387 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2388 std::numeric_limits<uint8_t>::max();
wub13d75452019-11-05 07:24:56 -08002389 new_ack_info.max_block_length =
2390 std::max(new_ack_info.max_block_length, interval.Length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002391 }
2392 return new_ack_info;
2393}
2394
2395bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2396 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002397 QuicPacketNumber base_packet_number;
2398 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002399 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2400 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2401 set_detailed_error("Unable to determine packet number space.");
2402 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2403 }
2404 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002405 } else {
2406 base_packet_number = largest_packet_number_;
2407 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002408 uint64_t full_packet_number;
2409 if (!ProcessAndCalculatePacketNumber(
2410 encrypted_reader, header->packet_number_length, base_packet_number,
2411 &full_packet_number)) {
2412 set_detailed_error("Unable to read packet number.");
2413 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2414 }
2415
dschinazi40f0b3d2020-02-19 17:54:05 -08002416 if (!IsValidFullPacketNumber(full_packet_number, version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002417 set_detailed_error("packet numbers cannot be 0.");
2418 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2419 }
2420 header->packet_number = QuicPacketNumber(full_packet_number);
2421
2422 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2423 set_detailed_error(
2424 "Visitor asked to stop processing of unauthenticated header.");
2425 return false;
2426 }
nharper3f283562019-05-02 16:37:12 -07002427 // The function we are in is called because the framer believes that it is
2428 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2429 // type. Usually, the framer makes that decision based on the framer's
2430 // version, but when the framer is used with Perspective::IS_SERVER, then
2431 // before version negotiation is complete (specifically, before
2432 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2433 // the type byte of the packet.
2434 //
2435 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2436 // to use the IETF packet header type. If that's the case and we're in this
2437 // function, then the packet received is invalid: the framer was expecting an
2438 // IETF packet header and didn't get one.
2439 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002440 set_detailed_error("Invalid public header type for expected version.");
2441 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2442 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002443 return true;
2444}
2445
2446bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2447 QuicPacketHeader* header) {
2448 uint8_t type;
2449 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002450 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002451 return false;
2452 }
dschinazi244f6dc2019-05-06 15:45:16 -07002453 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002454 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002455 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002456 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2457 // Version is always present in long headers.
2458 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002459 // In versions that do not support client connection IDs, we mark the
2460 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002461 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002462 (perspective_ == Perspective::IS_SERVER ||
2463 version_.SupportsClientConnectionIds())
2464 ? CONNECTION_ID_PRESENT
2465 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002466 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002467 (perspective_ == Perspective::IS_CLIENT ||
2468 version_.SupportsClientConnectionIds())
2469 ? CONNECTION_ID_PRESENT
2470 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002471 // Read version tag.
2472 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002473 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002474 set_detailed_error("Unable to read protocol version.");
2475 return false;
2476 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002477 if (!version_label) {
2478 // Version label is 0 indicating this is a version negotiation packet.
2479 header->long_packet_type = VERSION_NEGOTIATION;
2480 } else {
2481 header->version = ParseQuicVersionLabel(version_label);
2482 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayang36825da2019-08-21 14:01:27 -07002483 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002484 set_detailed_error("Fixed bit is 0 in long header.");
2485 return false;
2486 }
fayang36825da2019-08-21 14:01:27 -07002487 if (!GetLongHeaderType(type, &header->long_packet_type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002488 set_detailed_error("Illegal long header type value.");
2489 return false;
2490 }
dschinazi244f6dc2019-05-06 15:45:16 -07002491 if (header->long_packet_type == RETRY) {
2492 if (!version().SupportsRetry()) {
2493 set_detailed_error("RETRY not supported in this version.");
2494 return false;
2495 }
2496 if (perspective_ == Perspective::IS_SERVER) {
2497 set_detailed_error("Client-initiated RETRY is invalid.");
2498 return false;
2499 }
nharper55fa6132019-05-07 19:37:21 -07002500 } else if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002501 header->packet_number_length = GetLongHeaderPacketNumberLength(type);
nharper2ceb97c2019-04-19 11:38:59 -07002502 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002503 }
2504 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002505
2506 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2507 << QuicUtils::QuicLongHeaderTypetoString(
2508 header->long_packet_type);
2509 return true;
2510 }
2511
2512 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2513 // Version is not present in short headers.
2514 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002515 // In versions that do not support client connection IDs, the client will not
2516 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002517 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002518 (perspective_ == Perspective::IS_SERVER ||
2519 version_.SupportsClientConnectionIds())
2520 ? CONNECTION_ID_PRESENT
2521 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002522 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayang36825da2019-08-21 14:01:27 -07002523 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002524 set_detailed_error("Fixed bit is 0 in short header.");
2525 return false;
2526 }
dschinazidc770fc2020-01-13 15:42:41 -08002527 if (!version_.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002528 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002529 }
2530 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2531 return true;
2532}
2533
fayang40315542019-05-09 09:19:09 -07002534// static
2535bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2536 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002537 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002538 return false;
2539 }
fayang40315542019-05-09 09:19:09 -07002540 return true;
2541}
2542
2543// static
fayangccbab732019-05-13 10:11:25 -07002544bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2545 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002546 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002547 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002548 bool should_update_expected_server_connection_id_length,
2549 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002550 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002551 uint8_t* source_connection_id_length,
2552 std::string* detailed_error) {
2553 uint8_t connection_id_lengths_byte;
2554 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2555 *detailed_error = "Unable to read ConnectionId length.";
2556 return false;
2557 }
fayang40315542019-05-09 09:19:09 -07002558 uint8_t dcil =
2559 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2560 if (dcil != 0) {
2561 dcil += kConnectionIdLengthAdjustment;
2562 }
fayang40315542019-05-09 09:19:09 -07002563 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2564 if (scil != 0) {
2565 scil += kConnectionIdLengthAdjustment;
2566 }
dschinazi334f0232019-05-29 16:08:53 -07002567 if (should_update_expected_server_connection_id_length) {
2568 uint8_t server_connection_id_length =
2569 perspective == Perspective::IS_SERVER ? dcil : scil;
2570 if (*expected_server_connection_id_length != server_connection_id_length) {
2571 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2572 << static_cast<int>(*expected_server_connection_id_length)
2573 << " -> " << static_cast<int>(server_connection_id_length);
2574 *expected_server_connection_id_length = server_connection_id_length;
2575 }
2576 }
dschinazi8ff74822019-05-28 16:37:20 -07002577 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002578 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002579 scil != *source_connection_id_length) &&
dschinazi97da52b2020-01-13 15:44:43 -08002580 version.IsKnown() && !version.AllowsVariableLengthConnectionIds()) {
fayang40315542019-05-09 09:19:09 -07002581 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2582 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002583 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002584 return false;
2585 }
2586 *destination_connection_id_length = dcil;
2587 *source_connection_id_length = scil;
2588 return true;
2589}
2590
dschinazib953d022019-08-01 18:05:58 -07002591bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2592 if (!QuicUtils::IsConnectionIdValidForVersion(
2593 GetServerConnectionIdAsRecipient(header, perspective_),
2594 transport_version())) {
2595 set_detailed_error("Received server connection ID with invalid length.");
2596 return false;
2597 }
2598
2599 if (version_.SupportsClientConnectionIds() &&
2600 !QuicUtils::IsConnectionIdValidForVersion(
2601 GetClientConnectionIdAsRecipient(header, perspective_),
2602 transport_version())) {
2603 set_detailed_error("Received client connection ID with invalid length.");
2604 return false;
2605 }
2606 return true;
2607}
2608
QUICHE teama6ef0a62019-03-07 20:34:33 -05002609bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2610 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002611 if (version_.HasLengthPrefixedConnectionIds()) {
2612 uint8_t expected_destination_connection_id_length =
2613 perspective_ == Perspective::IS_CLIENT
2614 ? expected_client_connection_id_length_
2615 : expected_server_connection_id_length_;
2616 QuicVersionLabel version_label;
2617 bool has_length_prefix;
2618 std::string detailed_error;
2619 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2620 reader, expected_destination_connection_id_length,
2621 VersionHasIetfInvariantHeader(version_.transport_version),
2622 &header->type_byte, &header->form, &header->version_flag,
2623 &has_length_prefix, &version_label, &header->version,
2624 &header->destination_connection_id, &header->source_connection_id,
2625 &header->long_packet_type, &header->retry_token_length_length,
2626 &header->retry_token, &detailed_error);
2627 if (parse_result != QUIC_NO_ERROR) {
2628 set_detailed_error(detailed_error);
2629 return false;
2630 }
2631 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2632 header->source_connection_id_included =
2633 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2634 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2635 DCHECK(header->source_connection_id.IsEmpty());
2636 if (perspective_ == Perspective::IS_CLIENT) {
2637 header->source_connection_id = last_serialized_server_connection_id_;
2638 } else {
2639 header->source_connection_id = last_serialized_client_connection_id_;
2640 }
2641 }
dschinazib953d022019-08-01 18:05:58 -07002642
2643 if (!ValidateReceivedConnectionIds(*header)) {
2644 return false;
2645 }
2646
dschinazi48ac9192019-07-31 00:07:26 -07002647 if (header->version_flag &&
fayang36825da2019-08-21 14:01:27 -07002648 header->long_packet_type != VERSION_NEGOTIATION &&
dschinazi48ac9192019-07-31 00:07:26 -07002649 !(header->type_byte & FLAGS_FIXED_BIT)) {
2650 set_detailed_error("Fixed bit is 0 in long header.");
2651 return false;
2652 }
fayang36825da2019-08-21 14:01:27 -07002653 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
dschinazi48ac9192019-07-31 00:07:26 -07002654 set_detailed_error("Fixed bit is 0 in short header.");
2655 return false;
2656 }
2657 if (!header->version_flag) {
fayang36825da2019-08-21 14:01:27 -07002658 if (!version_.HasHeaderProtection()) {
2659 header->packet_number_length =
2660 GetShortHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002661 }
2662 return true;
2663 }
2664 if (header->long_packet_type == RETRY) {
2665 if (!version().SupportsRetry()) {
2666 set_detailed_error("RETRY not supported in this version.");
2667 return false;
2668 }
2669 if (perspective_ == Perspective::IS_SERVER) {
2670 set_detailed_error("Client-initiated RETRY is invalid.");
2671 return false;
2672 }
2673 return true;
2674 }
dschinazi97da52b2020-01-13 15:44:43 -08002675 if (header->version.IsKnown() && !header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002676 header->packet_number_length =
2677 GetLongHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002678 }
2679
2680 return true;
2681 }
2682
QUICHE teama6ef0a62019-03-07 20:34:33 -05002683 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2684 return false;
2685 }
2686
2687 uint8_t destination_connection_id_length =
2688 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002689 ? (perspective_ == Perspective::IS_SERVER
2690 ? expected_server_connection_id_length_
2691 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002692 : 0;
2693 uint8_t source_connection_id_length =
2694 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002695 ? (perspective_ == Perspective::IS_CLIENT
2696 ? expected_server_connection_id_length_
2697 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002698 : 0;
2699 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002700 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002701 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002702 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002703 &expected_server_connection_id_length_,
2704 &destination_connection_id_length, &source_connection_id_length,
2705 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002706 return false;
2707 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002708 }
2709
2710 // Read connection ID.
2711 if (!reader->ReadConnectionId(&header->destination_connection_id,
2712 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002713 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002714 return false;
2715 }
2716
2717 if (!reader->ReadConnectionId(&header->source_connection_id,
2718 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002719 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002720 return false;
2721 }
2722
dschinazi5e1a7b22019-07-31 12:23:21 -07002723 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2724 if (!header->source_connection_id.IsEmpty()) {
2725 DCHECK(!version_.SupportsClientConnectionIds());
2726 set_detailed_error("Client connection ID not supported in this version.");
2727 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002728 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002729 if (perspective_ == Perspective::IS_CLIENT) {
2730 header->source_connection_id = last_serialized_server_connection_id_;
2731 } else {
2732 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002733 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002734 }
2735
dschinazib953d022019-08-01 18:05:58 -07002736 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002737}
2738
2739bool QuicFramer::ProcessAndCalculatePacketNumber(
2740 QuicDataReader* reader,
2741 QuicPacketNumberLength packet_number_length,
2742 QuicPacketNumber base_packet_number,
2743 uint64_t* packet_number) {
2744 uint64_t wire_packet_number;
2745 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2746 return false;
2747 }
2748
2749 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2750 // in case the first guess is incorrect.
2751 *packet_number = CalculatePacketNumberFromWire(
2752 packet_number_length, base_packet_number, wire_packet_number);
2753 return true;
2754}
2755
2756bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2757 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002758 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2759 << "IETF QUIC Framing negotiated but attempting to process frames as "
2760 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002761 if (reader->IsDoneReading()) {
2762 set_detailed_error("Packet has no frames.");
2763 return RaiseError(QUIC_MISSING_PAYLOAD);
2764 }
dschinazi118934b2019-06-13 18:09:08 -07002765 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002766 while (!reader->IsDoneReading()) {
2767 uint8_t frame_type;
2768 if (!reader->ReadBytes(&frame_type, 1)) {
2769 set_detailed_error("Unable to read frame type.");
2770 return RaiseError(QUIC_INVALID_FRAME_DATA);
2771 }
fayang36825da2019-08-21 14:01:27 -07002772 const uint8_t special_mask = transport_version() <= QUIC_VERSION_43
QUICHE teama6ef0a62019-03-07 20:34:33 -05002773 ? kQuicFrameTypeBrokenMask
2774 : kQuicFrameTypeSpecialMask;
2775 if (frame_type & special_mask) {
2776 // Stream Frame
2777 if (frame_type & kQuicFrameTypeStreamMask) {
2778 QuicStreamFrame frame;
2779 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2780 return RaiseError(QUIC_INVALID_STREAM_DATA);
2781 }
dschinazi118934b2019-06-13 18:09:08 -07002782 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002783 if (!visitor_->OnStreamFrame(frame)) {
2784 QUIC_DVLOG(1) << ENDPOINT
2785 << "Visitor asked to stop further processing.";
2786 // Returning true since there was no parsing error.
2787 return true;
2788 }
2789 continue;
2790 }
2791
2792 // Ack Frame
2793 if (frame_type & kQuicFrameTypeAckMask) {
2794 if (!ProcessAckFrame(reader, frame_type)) {
2795 return RaiseError(QUIC_INVALID_ACK_DATA);
2796 }
dschinazi118934b2019-06-13 18:09:08 -07002797 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002798 continue;
2799 }
2800
2801 // This was a special frame type that did not match any
2802 // of the known ones. Error.
2803 set_detailed_error("Illegal frame type.");
2804 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2805 << static_cast<int>(frame_type);
2806 return RaiseError(QUIC_INVALID_FRAME_DATA);
2807 }
2808
2809 switch (frame_type) {
2810 case PADDING_FRAME: {
2811 QuicPaddingFrame frame;
2812 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002813 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002814 if (!visitor_->OnPaddingFrame(frame)) {
2815 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2816 // Returning true since there was no parsing error.
2817 return true;
2818 }
2819 continue;
2820 }
2821
2822 case RST_STREAM_FRAME: {
2823 QuicRstStreamFrame frame;
2824 if (!ProcessRstStreamFrame(reader, &frame)) {
2825 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2826 }
dschinazi118934b2019-06-13 18:09:08 -07002827 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002828 if (!visitor_->OnRstStreamFrame(frame)) {
2829 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2830 // Returning true since there was no parsing error.
2831 return true;
2832 }
2833 continue;
2834 }
2835
2836 case CONNECTION_CLOSE_FRAME: {
2837 QuicConnectionCloseFrame frame;
2838 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2839 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2840 }
2841
dschinazi118934b2019-06-13 18:09:08 -07002842 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2843 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002844 if (!visitor_->OnConnectionCloseFrame(frame)) {
2845 QUIC_DVLOG(1) << ENDPOINT
2846 << "Visitor asked to stop further processing.";
2847 // Returning true since there was no parsing error.
2848 return true;
2849 }
2850 continue;
2851 }
2852
2853 case GOAWAY_FRAME: {
2854 QuicGoAwayFrame goaway_frame;
2855 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2856 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2857 }
dschinazi118934b2019-06-13 18:09:08 -07002858 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2859 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002860 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2861 QUIC_DVLOG(1) << ENDPOINT
2862 << "Visitor asked to stop further processing.";
2863 // Returning true since there was no parsing error.
2864 return true;
2865 }
2866 continue;
2867 }
2868
2869 case WINDOW_UPDATE_FRAME: {
2870 QuicWindowUpdateFrame window_update_frame;
2871 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2872 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2873 }
dschinazi118934b2019-06-13 18:09:08 -07002874 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2875 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002876 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2877 QUIC_DVLOG(1) << ENDPOINT
2878 << "Visitor asked to stop further processing.";
2879 // Returning true since there was no parsing error.
2880 return true;
2881 }
2882 continue;
2883 }
2884
2885 case BLOCKED_FRAME: {
2886 QuicBlockedFrame blocked_frame;
2887 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2888 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2889 }
dschinazi118934b2019-06-13 18:09:08 -07002890 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2891 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002892 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2893 QUIC_DVLOG(1) << ENDPOINT
2894 << "Visitor asked to stop further processing.";
2895 // Returning true since there was no parsing error.
2896 return true;
2897 }
2898 continue;
2899 }
2900
2901 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002902 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayang36825da2019-08-21 14:01:27 -07002903 version_.transport_version > QUIC_VERSION_43) {
ianswett97b690b2019-05-02 15:12:43 -07002904 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2905 set_detailed_error("STOP WAITING not supported in version 44+.");
2906 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2907 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002908 QuicStopWaitingFrame stop_waiting_frame;
2909 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2910 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2911 }
dschinazi118934b2019-06-13 18:09:08 -07002912 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2913 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002914 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2915 QUIC_DVLOG(1) << ENDPOINT
2916 << "Visitor asked to stop further processing.";
2917 // Returning true since there was no parsing error.
2918 return true;
2919 }
2920 continue;
2921 }
2922 case PING_FRAME: {
2923 // Ping has no payload.
2924 QuicPingFrame ping_frame;
2925 if (!visitor_->OnPingFrame(ping_frame)) {
2926 QUIC_DVLOG(1) << ENDPOINT
2927 << "Visitor asked to stop further processing.";
2928 // Returning true since there was no parsing error.
2929 return true;
2930 }
dschinazi118934b2019-06-13 18:09:08 -07002931 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002932 continue;
2933 }
2934 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2935 QUIC_FALLTHROUGH_INTENDED;
2936 case IETF_EXTENSION_MESSAGE: {
2937 QuicMessageFrame message_frame;
2938 if (!ProcessMessageFrame(reader,
2939 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2940 &message_frame)) {
2941 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2942 }
dschinazi118934b2019-06-13 18:09:08 -07002943 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
2944 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002945 if (!visitor_->OnMessageFrame(message_frame)) {
2946 QUIC_DVLOG(1) << ENDPOINT
2947 << "Visitor asked to stop further processing.";
2948 // Returning true since there was no parsing error.
2949 return true;
2950 }
2951 break;
2952 }
2953 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07002954 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002955 set_detailed_error("Illegal frame type.");
2956 return RaiseError(QUIC_INVALID_FRAME_DATA);
2957 }
2958 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08002959 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002960 return RaiseError(QUIC_INVALID_FRAME_DATA);
2961 }
dschinazi118934b2019-06-13 18:09:08 -07002962 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002963 if (!visitor_->OnCryptoFrame(frame)) {
2964 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2965 // Returning true since there was no parsing error.
2966 return true;
2967 }
2968 break;
2969 }
2970
2971 default:
2972 set_detailed_error("Illegal frame type.");
2973 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2974 << static_cast<int>(frame_type);
2975 return RaiseError(QUIC_INVALID_FRAME_DATA);
2976 }
2977 }
2978
2979 return true;
2980}
2981
2982bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
2983 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002984 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
2985 << "Attempt to process frames as IETF frames but version ("
2986 << version_.transport_version << ") does not support IETF Framing.";
2987
QUICHE teama6ef0a62019-03-07 20:34:33 -05002988 if (reader->IsDoneReading()) {
2989 set_detailed_error("Packet has no frames.");
2990 return RaiseError(QUIC_MISSING_PAYLOAD);
2991 }
dschinazi118934b2019-06-13 18:09:08 -07002992
2993 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002994 while (!reader->IsDoneReading()) {
2995 uint64_t frame_type;
2996 // Will be the number of bytes into which frame_type was encoded.
2997 size_t encoded_bytes = reader->BytesRemaining();
2998 if (!reader->ReadVarInt62(&frame_type)) {
2999 set_detailed_error("Unable to read frame type.");
3000 return RaiseError(QUIC_INVALID_FRAME_DATA);
3001 }
fkastenholza3660102019-08-28 05:19:24 -07003002 current_received_frame_type_ = frame_type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003003
3004 // Is now the number of bytes into which the frame type was encoded.
3005 encoded_bytes -= reader->BytesRemaining();
3006
3007 // Check that the frame type is minimally encoded.
3008 if (encoded_bytes !=
3009 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3010 // The frame type was not minimally encoded.
3011 set_detailed_error("Frame type not minimally encoded.");
3012 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3013 }
3014
3015 if (IS_IETF_STREAM_FRAME(frame_type)) {
3016 QuicStreamFrame frame;
3017 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3018 return RaiseError(QUIC_INVALID_STREAM_DATA);
3019 }
dschinazi118934b2019-06-13 18:09:08 -07003020 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003021 if (!visitor_->OnStreamFrame(frame)) {
3022 QUIC_DVLOG(1) << ENDPOINT
3023 << "Visitor asked to stop further processing.";
3024 // Returning true since there was no parsing error.
3025 return true;
3026 }
3027 } else {
3028 switch (frame_type) {
3029 case IETF_PADDING: {
3030 QuicPaddingFrame frame;
3031 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003032 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3033 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003034 if (!visitor_->OnPaddingFrame(frame)) {
3035 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3036 // Returning true since there was no parsing error.
3037 return true;
3038 }
3039 break;
3040 }
3041 case IETF_RST_STREAM: {
3042 QuicRstStreamFrame frame;
3043 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3044 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3045 }
dschinazi118934b2019-06-13 18:09:08 -07003046 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3047 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003048 if (!visitor_->OnRstStreamFrame(frame)) {
3049 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3050 // Returning true since there was no parsing error.
3051 return true;
3052 }
3053 break;
3054 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003055 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003056 case IETF_CONNECTION_CLOSE: {
3057 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003058 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003059 reader,
3060 (frame_type == IETF_CONNECTION_CLOSE)
3061 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3062 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3063 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003064 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3065 }
dschinazi118934b2019-06-13 18:09:08 -07003066 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3067 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003068 if (!visitor_->OnConnectionCloseFrame(frame)) {
3069 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3070 // Returning true since there was no parsing error.
3071 return true;
3072 }
3073 break;
3074 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003075 case IETF_MAX_DATA: {
3076 QuicWindowUpdateFrame frame;
3077 if (!ProcessMaxDataFrame(reader, &frame)) {
3078 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3079 }
dschinazi118934b2019-06-13 18:09:08 -07003080 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3081 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003082 if (!visitor_->OnWindowUpdateFrame(frame)) {
3083 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3084 // Returning true since there was no parsing error.
3085 return true;
3086 }
3087 break;
3088 }
3089 case IETF_MAX_STREAM_DATA: {
3090 QuicWindowUpdateFrame frame;
3091 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3092 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3093 }
dschinazi118934b2019-06-13 18:09:08 -07003094 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3095 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003096 if (!visitor_->OnWindowUpdateFrame(frame)) {
3097 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3098 // Returning true since there was no parsing error.
3099 return true;
3100 }
3101 break;
3102 }
3103 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3104 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003105 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003106 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003107 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003108 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003109 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003110 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3111 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003112 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003113 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3114 // Returning true since there was no parsing error.
3115 return true;
3116 }
3117 break;
3118 }
3119 case IETF_PING: {
3120 // Ping has no payload.
3121 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003122 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3123 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003124 if (!visitor_->OnPingFrame(ping_frame)) {
3125 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3126 // Returning true since there was no parsing error.
3127 return true;
3128 }
3129 break;
3130 }
ianswett2f077442019-12-12 11:51:24 -08003131 case IETF_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003132 QuicBlockedFrame frame;
3133 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3134 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3135 }
dschinazi118934b2019-06-13 18:09:08 -07003136 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3137 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003138 if (!visitor_->OnBlockedFrame(frame)) {
3139 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3140 // Returning true since there was no parsing error.
3141 return true;
3142 }
3143 break;
3144 }
ianswett2f077442019-12-12 11:51:24 -08003145 case IETF_STREAM_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003146 QuicBlockedFrame frame;
3147 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3148 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3149 }
dschinazi118934b2019-06-13 18:09:08 -07003150 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3151 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003152 if (!visitor_->OnBlockedFrame(frame)) {
3153 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3154 // Returning true since there was no parsing error.
3155 return true;
3156 }
3157 break;
3158 }
3159 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3160 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003161 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003162 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003163 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003164 }
dschinazi118934b2019-06-13 18:09:08 -07003165 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3166 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003167 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003168 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3169 // Returning true since there was no parsing error.
3170 return true;
3171 }
3172 break;
3173 }
3174 case IETF_NEW_CONNECTION_ID: {
3175 QuicNewConnectionIdFrame frame;
3176 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3177 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3178 }
dschinazi118934b2019-06-13 18:09:08 -07003179 QUIC_DVLOG(2) << ENDPOINT
3180 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003181 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3182 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3183 // Returning true since there was no parsing error.
3184 return true;
3185 }
3186 break;
3187 }
3188 case IETF_RETIRE_CONNECTION_ID: {
3189 QuicRetireConnectionIdFrame frame;
3190 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3191 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3192 }
dschinazi118934b2019-06-13 18:09:08 -07003193 QUIC_DVLOG(2) << ENDPOINT
3194 << "Processing IETF retire connection ID frame "
3195 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003196 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3197 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3198 // Returning true since there was no parsing error.
3199 return true;
3200 }
3201 break;
3202 }
3203 case IETF_NEW_TOKEN: {
3204 QuicNewTokenFrame frame;
3205 if (!ProcessNewTokenFrame(reader, &frame)) {
3206 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3207 }
dschinazi118934b2019-06-13 18:09:08 -07003208 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3209 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003210 if (!visitor_->OnNewTokenFrame(frame)) {
3211 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3212 // Returning true since there was no parsing error.
3213 return true;
3214 }
3215 break;
3216 }
3217 case IETF_STOP_SENDING: {
3218 QuicStopSendingFrame frame;
3219 if (!ProcessStopSendingFrame(reader, &frame)) {
3220 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3221 }
dschinazi118934b2019-06-13 18:09:08 -07003222 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3223 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003224 if (!visitor_->OnStopSendingFrame(frame)) {
3225 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3226 // Returning true since there was no parsing error.
3227 return true;
3228 }
3229 break;
3230 }
3231 case IETF_ACK_ECN:
3232 case IETF_ACK: {
3233 QuicAckFrame frame;
3234 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3235 return RaiseError(QUIC_INVALID_ACK_DATA);
3236 }
dschinazi118934b2019-06-13 18:09:08 -07003237 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003238 break;
3239 }
3240 case IETF_PATH_CHALLENGE: {
3241 QuicPathChallengeFrame frame;
3242 if (!ProcessPathChallengeFrame(reader, &frame)) {
3243 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3244 }
dschinazi118934b2019-06-13 18:09:08 -07003245 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3246 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003247 if (!visitor_->OnPathChallengeFrame(frame)) {
3248 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3249 // Returning true since there was no parsing error.
3250 return true;
3251 }
3252 break;
3253 }
3254 case IETF_PATH_RESPONSE: {
3255 QuicPathResponseFrame frame;
3256 if (!ProcessPathResponseFrame(reader, &frame)) {
3257 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3258 }
dschinazi118934b2019-06-13 18:09:08 -07003259 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3260 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003261 if (!visitor_->OnPathResponseFrame(frame)) {
3262 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3263 // Returning true since there was no parsing error.
3264 return true;
3265 }
3266 break;
3267 }
dschinazicd86dd12019-11-14 10:11:13 -08003268 case IETF_EXTENSION_MESSAGE_NO_LENGTH_V99:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003269 QUIC_FALLTHROUGH_INTENDED;
dschinazicd86dd12019-11-14 10:11:13 -08003270 case IETF_EXTENSION_MESSAGE_V99: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003271 QuicMessageFrame message_frame;
3272 if (!ProcessMessageFrame(
dschinazicd86dd12019-11-14 10:11:13 -08003273 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH_V99,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003274 &message_frame)) {
3275 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3276 }
dschinazi118934b2019-06-13 18:09:08 -07003277 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3278 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003279 if (!visitor_->OnMessageFrame(message_frame)) {
3280 QUIC_DVLOG(1) << ENDPOINT
3281 << "Visitor asked to stop further processing.";
3282 // Returning true since there was no parsing error.
3283 return true;
3284 }
3285 break;
3286 }
3287 case IETF_CRYPTO: {
3288 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08003289 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003290 return RaiseError(QUIC_INVALID_FRAME_DATA);
3291 }
dschinazi118934b2019-06-13 18:09:08 -07003292 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003293 if (!visitor_->OnCryptoFrame(frame)) {
3294 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3295 // Returning true since there was no parsing error.
3296 return true;
3297 }
3298 break;
3299 }
fayang01062942020-01-22 07:23:23 -08003300 case IETF_HANDSHAKE_DONE: {
3301 // HANDSHAKE_DONE has no payload.
3302 QuicHandshakeDoneFrame handshake_done_frame;
3303 if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) {
3304 QUIC_DVLOG(1) << ENDPOINT
3305 << "Visitor asked to stop further processing.";
3306 // Returning true since there was no parsing error.
3307 return true;
3308 }
3309 QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame "
3310 << handshake_done_frame;
3311 break;
3312 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003313
3314 default:
3315 set_detailed_error("Illegal frame type.");
3316 QUIC_DLOG(WARNING)
3317 << ENDPOINT
3318 << "Illegal frame type: " << static_cast<int>(frame_type);
3319 return RaiseError(QUIC_INVALID_FRAME_DATA);
3320 }
3321 }
3322 }
3323 return true;
3324}
3325
3326namespace {
3327// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3328inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3329 return (1u << num_bits) - 1;
3330}
3331
3332// Extract |num_bits| from |flags| offset by |offset|.
3333uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3334 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3335}
3336
3337// Extract the bit at position |offset| from |flags| as a bool.
3338bool ExtractBit(uint8_t flags, uint8_t offset) {
3339 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3340}
3341
3342// Set |num_bits|, offset by |offset| to |val| in |flags|.
3343void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3344 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3345 *flags |= val << offset;
3346}
3347
3348// Set the bit at position |offset| to |val| in |flags|.
3349void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3350 SetBits(flags, val ? 1 : 0, 1, offset);
3351}
3352} // namespace
3353
3354bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3355 uint8_t frame_type,
3356 QuicStreamFrame* frame) {
3357 uint8_t stream_flags = frame_type;
3358
3359 uint8_t stream_id_length = 0;
3360 uint8_t offset_length = 4;
3361 bool has_data_length = true;
3362 stream_flags &= ~kQuicFrameTypeStreamMask;
3363
3364 // Read from right to left: StreamID, Offset, Data Length, Fin.
3365 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3366 stream_flags >>= kQuicStreamIdShift;
3367
3368 offset_length = (stream_flags & kQuicStreamOffsetMask);
3369 // There is no encoding for 1 byte, only 0 and 2 through 8.
3370 if (offset_length > 0) {
3371 offset_length += 1;
3372 }
3373 stream_flags >>= kQuicStreamShift;
3374
3375 has_data_length =
3376 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3377 stream_flags >>= kQuicStreamDataLengthShift;
3378
3379 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3380
3381 uint64_t stream_id;
3382 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3383 set_detailed_error("Unable to read stream_id.");
3384 return false;
3385 }
3386 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3387
3388 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3389 set_detailed_error("Unable to read offset.");
3390 return false;
3391 }
3392
dmcardlecf0bfcf2019-12-13 08:08:21 -08003393 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3394 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003395 if (has_data_length) {
3396 if (!reader->ReadStringPiece16(&data)) {
3397 set_detailed_error("Unable to read frame data.");
3398 return false;
3399 }
3400 } else {
3401 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3402 set_detailed_error("Unable to read frame data.");
3403 return false;
3404 }
3405 }
3406 frame->data_buffer = data.data();
3407 frame->data_length = static_cast<uint16_t>(data.length());
3408
3409 return true;
3410}
3411
3412bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3413 uint8_t frame_type,
3414 QuicStreamFrame* frame) {
3415 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003416 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003417 set_detailed_error("Unable to read stream_id.");
3418 return false;
3419 }
3420
3421 // If we have a data offset, read it. If not, set to 0.
3422 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3423 if (!reader->ReadVarInt62(&frame->offset)) {
3424 set_detailed_error("Unable to read stream data offset.");
3425 return false;
3426 }
3427 } else {
3428 // no offset in the frame, ensure it's 0 in the Frame.
3429 frame->offset = 0;
3430 }
3431
3432 // If we have a data length, read it. If not, set to 0.
3433 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3434 QuicIetfStreamDataLength length;
3435 if (!reader->ReadVarInt62(&length)) {
3436 set_detailed_error("Unable to read stream data length.");
3437 return false;
3438 }
3439 if (length > 0xffff) {
3440 set_detailed_error("Stream data length is too large.");
3441 return false;
3442 }
3443 frame->data_length = length;
3444 } else {
3445 // no length in the frame, it is the number of bytes remaining in the
3446 // packet.
3447 frame->data_length = reader->BytesRemaining();
3448 }
3449
3450 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3451 frame->fin = true;
3452 } else {
3453 frame->fin = false;
3454 }
3455
dmcardlecf0bfcf2019-12-13 08:08:21 -08003456 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3457 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003458 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3459 set_detailed_error("Unable to read frame data.");
3460 return false;
3461 }
3462 frame->data_buffer = data.data();
3463 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3464
3465 return true;
3466}
3467
3468bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
renjietang15dfaa82020-01-03 16:13:38 -08003469 EncryptionLevel encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003470 QuicCryptoFrame* frame) {
renjietang15dfaa82020-01-03 16:13:38 -08003471 frame->level = encryption_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003472 if (!reader->ReadVarInt62(&frame->offset)) {
3473 set_detailed_error("Unable to read crypto data offset.");
3474 return false;
3475 }
3476 uint64_t len;
3477 if (!reader->ReadVarInt62(&len) ||
3478 len > std::numeric_limits<QuicPacketLength>::max()) {
3479 set_detailed_error("Invalid data length.");
3480 return false;
3481 }
3482 frame->data_length = len;
3483
dmcardlecf0bfcf2019-12-13 08:08:21 -08003484 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3485 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003486 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3487 set_detailed_error("Unable to read frame data.");
3488 return false;
3489 }
3490 frame->data_buffer = data.data();
3491 return true;
3492}
3493
3494bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3495 const bool has_ack_blocks =
3496 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3497 uint8_t num_ack_blocks = 0;
3498 uint8_t num_received_packets = 0;
3499
3500 // Determine the two lengths from the frame type: largest acked length,
3501 // ack block length.
3502 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003503 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3504 kActBlockLengthOffset));
3505 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003506 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3507 kLargestAckedOffset));
3508
3509 uint64_t largest_acked;
3510 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3511 set_detailed_error("Unable to read largest acked.");
3512 return false;
3513 }
3514
3515 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3516 // Connection always sends packet starting from kFirstSendingPacketNumber >
3517 // 0, peer has observed an unsent packet.
3518 set_detailed_error("Largest acked is 0.");
3519 return false;
3520 }
3521
3522 uint64_t ack_delay_time_us;
3523 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3524 set_detailed_error("Unable to read ack delay time.");
3525 return false;
3526 }
3527
3528 if (!visitor_->OnAckFrameStart(
3529 QuicPacketNumber(largest_acked),
3530 ack_delay_time_us == kUFloat16MaxValue
3531 ? QuicTime::Delta::Infinite()
3532 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3533 // The visitor suppresses further processing of the packet. Although this is
3534 // not a parsing error, returns false as this is in middle of processing an
3535 // ack frame,
3536 set_detailed_error("Visitor suppresses further processing of ack frame.");
3537 return false;
3538 }
3539
3540 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3541 set_detailed_error("Unable to read num of ack blocks.");
3542 return false;
3543 }
3544
3545 uint64_t first_block_length;
3546 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3547 set_detailed_error("Unable to read first ack block length.");
3548 return false;
3549 }
3550
3551 if (first_block_length == 0) {
3552 set_detailed_error("First block length is zero.");
3553 return false;
3554 }
3555 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3556 if (first_block_length + first_sending_packet_number_.ToUint64() >
3557 largest_acked + 1) {
3558 first_ack_block_underflow = true;
3559 }
3560 if (first_ack_block_underflow) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003561 set_detailed_error(
3562 quiche::QuicheStrCat("Underflow with first ack block length ",
3563 first_block_length, " largest acked is ",
3564 largest_acked, ".")
3565 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003566 return false;
3567 }
3568
3569 uint64_t first_received = largest_acked + 1 - first_block_length;
3570 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3571 QuicPacketNumber(largest_acked + 1))) {
3572 // The visitor suppresses further processing of the packet. Although
3573 // this is not a parsing error, returns false as this is in middle
3574 // of processing an ack frame,
3575 set_detailed_error("Visitor suppresses further processing of ack frame.");
3576 return false;
3577 }
3578
3579 if (num_ack_blocks > 0) {
3580 for (size_t i = 0; i < num_ack_blocks; ++i) {
3581 uint8_t gap = 0;
3582 if (!reader->ReadUInt8(&gap)) {
3583 set_detailed_error("Unable to read gap to next ack block.");
3584 return false;
3585 }
3586 uint64_t current_block_length;
3587 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3588 set_detailed_error("Unable to ack block length.");
3589 return false;
3590 }
3591 bool ack_block_underflow = first_received < gap + current_block_length;
3592 if (first_received < gap + current_block_length +
3593 first_sending_packet_number_.ToUint64()) {
3594 ack_block_underflow = true;
3595 }
3596 if (ack_block_underflow) {
3597 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003598 quiche::QuicheStrCat("Underflow with ack block length ",
3599 current_block_length, ", end of block is ",
3600 first_received - gap, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003601 .c_str());
3602 return false;
3603 }
3604
3605 first_received -= (gap + current_block_length);
3606 if (current_block_length > 0) {
3607 if (!visitor_->OnAckRange(
3608 QuicPacketNumber(first_received),
3609 QuicPacketNumber(first_received) + current_block_length)) {
3610 // The visitor suppresses further processing of the packet. Although
3611 // this is not a parsing error, returns false as this is in middle
3612 // of processing an ack frame,
3613 set_detailed_error(
3614 "Visitor suppresses further processing of ack frame.");
3615 return false;
3616 }
3617 }
3618 }
3619 }
3620
3621 if (!reader->ReadUInt8(&num_received_packets)) {
3622 set_detailed_error("Unable to read num received packets.");
3623 return false;
3624 }
3625
3626 if (!ProcessTimestampsInAckFrame(num_received_packets,
3627 QuicPacketNumber(largest_acked), reader)) {
3628 return false;
3629 }
3630
3631 // Done processing the ACK frame.
fayang533cb1b2020-01-28 08:05:08 -08003632 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(first_received))) {
3633 set_detailed_error(
3634 "Error occurs when visitor finishes processing the ACK frame.");
3635 return false;
3636 }
3637
3638 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003639}
3640
3641bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3642 QuicPacketNumber largest_acked,
3643 QuicDataReader* reader) {
3644 if (num_received_packets == 0) {
3645 return true;
3646 }
3647 uint8_t delta_from_largest_observed;
3648 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3649 set_detailed_error("Unable to read sequence delta in received packets.");
3650 return false;
3651 }
3652
3653 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003654 set_detailed_error(
3655 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3656 delta_from_largest_observed,
3657 ", largest_acked: ", largest_acked.ToUint64())
3658 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003659 return false;
3660 }
3661
3662 // Time delta from the framer creation.
3663 uint32_t time_delta_us;
3664 if (!reader->ReadUInt32(&time_delta_us)) {
3665 set_detailed_error("Unable to read time delta in received packets.");
3666 return false;
3667 }
3668
3669 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3670 if (process_timestamps_) {
3671 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3672
3673 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3674 }
3675
3676 for (uint8_t i = 1; i < num_received_packets; ++i) {
3677 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3678 set_detailed_error("Unable to read sequence delta in received packets.");
3679 return false;
3680 }
3681 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3682 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003683 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3684 delta_from_largest_observed,
3685 ", largest_acked: ", largest_acked.ToUint64())
QUICHE teama6ef0a62019-03-07 20:34:33 -05003686 .c_str());
3687 return false;
3688 }
3689 seq_num = largest_acked - delta_from_largest_observed;
3690
3691 // Time delta from the previous timestamp.
3692 uint64_t incremental_time_delta_us;
3693 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3694 set_detailed_error(
3695 "Unable to read incremental time delta in received packets.");
3696 return false;
3697 }
3698
3699 if (process_timestamps_) {
3700 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3701 incremental_time_delta_us);
3702 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3703 }
3704 }
3705 return true;
3706}
3707
3708bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3709 uint64_t frame_type,
3710 QuicAckFrame* ack_frame) {
3711 uint64_t largest_acked;
3712 if (!reader->ReadVarInt62(&largest_acked)) {
3713 set_detailed_error("Unable to read largest acked.");
3714 return false;
3715 }
3716 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3717 // Connection always sends packet starting from kFirstSendingPacketNumber >
3718 // 0, peer has observed an unsent packet.
3719 set_detailed_error("Largest acked is 0.");
3720 return false;
3721 }
3722 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3723 uint64_t ack_delay_time_in_us;
3724 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3725 set_detailed_error("Unable to read ack delay time.");
3726 return false;
3727 }
3728
fayang3371b092019-12-04 07:08:52 -08003729 if (ack_delay_time_in_us >= (kVarInt62MaxValue >> peer_ack_delay_exponent_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003730 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3731 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003732 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003733 ack_frame->ack_delay_time =
3734 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3735 }
3736 if (frame_type == IETF_ACK_ECN) {
3737 ack_frame->ecn_counters_populated = true;
3738 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3739 set_detailed_error("Unable to read ack ect_0_count.");
3740 return false;
3741 }
3742 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3743 set_detailed_error("Unable to read ack ect_1_count.");
3744 return false;
3745 }
3746 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3747 set_detailed_error("Unable to read ack ecn_ce_count.");
3748 return false;
3749 }
3750 } else {
3751 ack_frame->ecn_counters_populated = false;
3752 ack_frame->ect_0_count = 0;
3753 ack_frame->ect_1_count = 0;
3754 ack_frame->ecn_ce_count = 0;
3755 }
3756 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3757 ack_frame->ack_delay_time)) {
3758 // The visitor suppresses further processing of the packet. Although this is
3759 // not a parsing error, returns false as this is in middle of processing an
3760 // ACK frame.
3761 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3762 return false;
3763 }
3764
3765 // Get number of ACK blocks from the packet.
3766 uint64_t ack_block_count;
3767 if (!reader->ReadVarInt62(&ack_block_count)) {
3768 set_detailed_error("Unable to read ack block count.");
3769 return false;
3770 }
3771 // There always is a first ACK block, which is the (number of packets being
3772 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3773 // value is 0, then only largest is acked. If it is 1, then largest-1,
3774 // largest] are acked, etc
3775 uint64_t ack_block_value;
3776 if (!reader->ReadVarInt62(&ack_block_value)) {
3777 set_detailed_error("Unable to read first ack block length.");
3778 return false;
3779 }
3780 // Calculate the packets being acked in the first block.
3781 // +1 because AddRange implementation requires [low,high)
3782 uint64_t block_high = largest_acked + 1;
3783 uint64_t block_low = largest_acked - ack_block_value;
3784
3785 // ack_block_value is the number of packets preceding the
3786 // largest_acked packet which are in the block being acked. Thus,
3787 // its maximum value is largest_acked-1. Test this, reporting an
3788 // error if the value is wrong.
3789 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3790 largest_acked) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003791 set_detailed_error(
3792 quiche::QuicheStrCat("Underflow with first ack block length ",
3793 ack_block_value + 1, " largest acked is ",
3794 largest_acked, ".")
3795 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003796 return false;
3797 }
3798
3799 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3800 QuicPacketNumber(block_high))) {
3801 // The visitor suppresses further processing of the packet. Although
3802 // this is not a parsing error, returns false as this is in middle
3803 // of processing an ACK frame.
3804 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3805 return false;
3806 }
3807
3808 while (ack_block_count != 0) {
3809 uint64_t gap_block_value;
3810 // Get the sizes of the gap and ack blocks,
3811 if (!reader->ReadVarInt62(&gap_block_value)) {
3812 set_detailed_error("Unable to read gap block value.");
3813 return false;
3814 }
3815 // It's an error if the gap is larger than the space from packet
3816 // number 0 to the start of the block that's just been acked, PLUS
3817 // there must be space for at least 1 packet to be acked. For
3818 // example, if block_low is 10 and gap_block_value is 9, it means
3819 // the gap block is 10 packets long, leaving no room for a packet
3820 // to be acked. Thus, gap_block_value+2 can not be larger than
3821 // block_low.
3822 // The test is written this way to detect wrap-arounds.
3823 if ((gap_block_value + 2) > block_low) {
3824 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003825 quiche::QuicheStrCat("Underflow with gap block length ",
3826 gap_block_value + 1,
3827 " previous ack block start is ", block_low, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003828 .c_str());
3829 return false;
3830 }
3831
3832 // Adjust block_high to be the top of the next ack block.
3833 // There is a gap of |gap_block_value| packets between the bottom
3834 // of ack block N and top of block N+1. Note that gap_block_value
3835 // is he size of the gap minus 1 (per the QUIC protocol), and
3836 // block_high is the packet number of the first packet of the gap
3837 // (per the implementation of OnAckRange/AddAckRange, below).
3838 block_high = block_low - 1 - gap_block_value;
3839
3840 if (!reader->ReadVarInt62(&ack_block_value)) {
3841 set_detailed_error("Unable to read ack block value.");
3842 return false;
3843 }
3844 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3845 (block_high - 1)) {
3846 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003847 quiche::QuicheStrCat("Underflow with ack block length ",
3848 ack_block_value + 1, " latest ack block end is ",
3849 block_high - 1, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003850 .c_str());
3851 return false;
3852 }
3853 // Calculate the low end of the new nth ack block. The +1 is
3854 // because the encoded value is the blocksize-1.
3855 block_low = block_high - 1 - ack_block_value;
3856 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3857 QuicPacketNumber(block_high))) {
3858 // The visitor suppresses further processing of the packet. Although
3859 // this is not a parsing error, returns false as this is in middle
3860 // of processing an ACK frame.
3861 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3862 return false;
3863 }
3864
3865 // Another one done.
3866 ack_block_count--;
3867 }
3868
fayang533cb1b2020-01-28 08:05:08 -08003869 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(block_low))) {
3870 set_detailed_error(
3871 "Error occurs when visitor finishes processing the ACK frame.");
3872 return false;
3873 }
3874
3875 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003876}
3877
3878bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3879 const QuicPacketHeader& header,
3880 QuicStopWaitingFrame* stop_waiting) {
3881 uint64_t least_unacked_delta;
3882 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3883 &least_unacked_delta)) {
3884 set_detailed_error("Unable to read least unacked delta.");
3885 return false;
3886 }
3887 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3888 set_detailed_error("Invalid unacked delta.");
3889 return false;
3890 }
3891 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3892
3893 return true;
3894}
3895
3896bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3897 QuicRstStreamFrame* frame) {
3898 if (!reader->ReadUInt32(&frame->stream_id)) {
3899 set_detailed_error("Unable to read stream_id.");
3900 return false;
3901 }
3902
3903 if (!reader->ReadUInt64(&frame->byte_offset)) {
3904 set_detailed_error("Unable to read rst stream sent byte offset.");
3905 return false;
3906 }
3907
3908 uint32_t error_code;
3909 if (!reader->ReadUInt32(&error_code)) {
3910 set_detailed_error("Unable to read rst stream error code.");
3911 return false;
3912 }
3913
3914 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3915 // Ignore invalid stream error code if any.
3916 error_code = QUIC_STREAM_LAST_ERROR;
3917 }
3918
3919 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3920
3921 return true;
3922}
3923
3924bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3925 QuicConnectionCloseFrame* frame) {
3926 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003927 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3928
QUICHE teama6ef0a62019-03-07 20:34:33 -05003929 if (!reader->ReadUInt32(&error_code)) {
3930 set_detailed_error("Unable to read connection close error code.");
3931 return false;
3932 }
3933
3934 if (error_code >= QUIC_LAST_ERROR) {
3935 // Ignore invalid QUIC error code if any.
3936 error_code = QUIC_LAST_ERROR;
3937 }
3938
fkastenholze9d71a82019-04-09 05:12:13 -07003939 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003940
fkastenholza14a7ae2019-08-07 05:21:22 -07003941 // For Google QUIC connection closes, copy the Google QUIC error code to
3942 // the extracted error code field so that the Google QUIC error code is always
3943 // available in extracted_error_code.
3944 frame->extracted_error_code = frame->quic_error_code;
3945
dmcardlecf0bfcf2019-12-13 08:08:21 -08003946 quiche::QuicheStringPiece error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003947 if (!reader->ReadStringPiece16(&error_details)) {
3948 set_detailed_error("Unable to read connection close error details.");
3949 return false;
3950 }
vasilvvc48c8712019-03-11 13:38:16 -07003951 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003952
3953 return true;
3954}
3955
3956bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3957 QuicGoAwayFrame* frame) {
3958 uint32_t error_code;
3959 if (!reader->ReadUInt32(&error_code)) {
3960 set_detailed_error("Unable to read go away error code.");
3961 return false;
3962 }
3963
3964 if (error_code >= QUIC_LAST_ERROR) {
3965 // Ignore invalid QUIC error code if any.
3966 error_code = QUIC_LAST_ERROR;
3967 }
3968 frame->error_code = static_cast<QuicErrorCode>(error_code);
3969
3970 uint32_t stream_id;
3971 if (!reader->ReadUInt32(&stream_id)) {
3972 set_detailed_error("Unable to read last good stream id.");
3973 return false;
3974 }
3975 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
3976
dmcardlecf0bfcf2019-12-13 08:08:21 -08003977 quiche::QuicheStringPiece reason_phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003978 if (!reader->ReadStringPiece16(&reason_phrase)) {
3979 set_detailed_error("Unable to read goaway reason.");
3980 return false;
3981 }
vasilvvc48c8712019-03-11 13:38:16 -07003982 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003983
3984 return true;
3985}
3986
3987bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
3988 QuicWindowUpdateFrame* frame) {
3989 if (!reader->ReadUInt32(&frame->stream_id)) {
3990 set_detailed_error("Unable to read stream_id.");
3991 return false;
3992 }
3993
renjietangd088eab2019-11-21 14:54:41 -08003994 if (!reader->ReadUInt64(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003995 set_detailed_error("Unable to read window byte_offset.");
3996 return false;
3997 }
3998
3999 return true;
4000}
4001
4002bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4003 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004004 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4005 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004006
4007 if (!reader->ReadUInt32(&frame->stream_id)) {
4008 set_detailed_error("Unable to read stream_id.");
4009 return false;
4010 }
4011
4012 return true;
4013}
4014
4015void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4016 QuicPaddingFrame* frame) {
4017 // Type byte has been read.
4018 frame->num_padding_bytes = 1;
4019 uint8_t next_byte;
4020 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4021 reader->ReadBytes(&next_byte, 1);
4022 DCHECK_EQ(0x00, next_byte);
4023 ++frame->num_padding_bytes;
4024 }
4025}
4026
4027bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4028 bool no_message_length,
4029 QuicMessageFrame* frame) {
4030 if (no_message_length) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08004031 quiche::QuicheStringPiece remaining(reader->ReadRemainingPayload());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004032 frame->data = remaining.data();
4033 frame->message_length = remaining.length();
4034 return true;
4035 }
4036
4037 uint64_t message_length;
4038 if (!reader->ReadVarInt62(&message_length)) {
4039 set_detailed_error("Unable to read message length");
4040 return false;
4041 }
4042
dmcardlecf0bfcf2019-12-13 08:08:21 -08004043 quiche::QuicheStringPiece message_piece;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004044 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4045 set_detailed_error("Unable to read message data");
4046 return false;
4047 }
4048
4049 frame->data = message_piece.data();
4050 frame->message_length = message_length;
4051
4052 return true;
4053}
4054
4055// static
dmcardlecf0bfcf2019-12-13 08:08:21 -08004056quiche::QuicheStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004057 QuicTransportVersion version,
4058 const QuicEncryptedPacket& encrypted,
4059 QuicConnectionIdLength destination_connection_id_length,
4060 QuicConnectionIdLength source_connection_id_length,
4061 bool includes_version,
4062 bool includes_diversification_nonce,
4063 QuicPacketNumberLength packet_number_length,
4064 QuicVariableLengthIntegerLength retry_token_length_length,
4065 uint64_t retry_token_length,
4066 QuicVariableLengthIntegerLength length_length) {
4067 // TODO(ianswett): This is identical to QuicData::AssociatedData.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004068 return quiche::QuicheStringPiece(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004069 encrypted.data(),
4070 GetStartOfEncryptedData(version, destination_connection_id_length,
4071 source_connection_id_length, includes_version,
4072 includes_diversification_nonce,
4073 packet_number_length, retry_token_length_length,
4074 retry_token_length, length_length));
4075}
4076
4077void QuicFramer::SetDecrypter(EncryptionLevel level,
4078 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004079 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004080 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004081 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004082 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004083 << EncryptionLevelToString(decrypter_level_) << " to "
4084 << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004085 decrypter_[decrypter_level_] = nullptr;
4086 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004087 decrypter_level_ = level;
4088}
4089
4090void QuicFramer::SetAlternativeDecrypter(
4091 EncryptionLevel level,
4092 std::unique_ptr<QuicDecrypter> decrypter,
4093 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004094 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004095 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004096 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004097 << EncryptionLevelToString(alternative_decrypter_level_)
4098 << " to " << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004099 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4100 decrypter_[alternative_decrypter_level_] = nullptr;
4101 }
4102 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004103 alternative_decrypter_level_ = level;
4104 alternative_decrypter_latch_ = latch_once_used;
4105}
4106
zhongyi546cc452019-04-12 15:27:49 -07004107void QuicFramer::InstallDecrypter(EncryptionLevel level,
4108 std::unique_ptr<QuicDecrypter> decrypter) {
4109 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004110 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004111 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004112 decrypter_[level] = std::move(decrypter);
4113}
4114
4115void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4116 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004117 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004118 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004119 decrypter_[level] = nullptr;
4120}
4121
4122const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4123 DCHECK(version_.KnowsWhichDecrypterToUse());
4124 return decrypter_[level].get();
4125}
4126
QUICHE teama6ef0a62019-03-07 20:34:33 -05004127const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004128 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004129}
4130
4131const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004132 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4133 return nullptr;
4134 }
4135 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004136}
4137
4138void QuicFramer::SetEncrypter(EncryptionLevel level,
4139 std::unique_ptr<QuicEncrypter> encrypter) {
4140 DCHECK_GE(level, 0);
4141 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
dschinazi4b5a68a2019-08-15 15:45:36 -07004142 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004143 << EncryptionLevelToString(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004144 encrypter_[level] = std::move(encrypter);
4145}
4146
fayangb296fb82020-02-11 08:14:28 -08004147void QuicFramer::RemoveEncrypter(EncryptionLevel level) {
4148 QUIC_DVLOG(1) << ENDPOINT << "Removing encrypter of "
4149 << EncryptionLevelToString(level);
4150 encrypter_[level] = nullptr;
4151}
4152
nharper4a5a76c2019-09-13 13:44:37 -07004153void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) {
4154 CrypterPair crypters;
4155 CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id,
4156 &crypters);
4157 encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter);
4158 decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter);
4159}
4160
QUICHE teama6ef0a62019-03-07 20:34:33 -05004161size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4162 QuicPacketNumber packet_number,
4163 size_t ad_len,
4164 size_t total_len,
4165 size_t buffer_len,
4166 char* buffer) {
4167 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004168 if (encrypter_[level] == nullptr) {
4169 QUIC_BUG << ENDPOINT
4170 << "Attempted to encrypt in place without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004171 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004172 RaiseError(QUIC_ENCRYPTION_FAILURE);
4173 return 0;
4174 }
4175
QUICHE teama6ef0a62019-03-07 20:34:33 -05004176 size_t output_length = 0;
4177 if (!encrypter_[level]->EncryptPacket(
4178 packet_number.ToUint64(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08004179 quiche::QuicheStringPiece(buffer, ad_len), // Associated data
4180 quiche::QuicheStringPiece(buffer + ad_len,
4181 total_len - ad_len), // Plaintext
4182 buffer + ad_len, // Destination buffer
QUICHE teama6ef0a62019-03-07 20:34:33 -05004183 &output_length, buffer_len - ad_len)) {
4184 RaiseError(QUIC_ENCRYPTION_FAILURE);
4185 return 0;
4186 }
nharper55fa6132019-05-07 19:37:21 -07004187 if (version_.HasHeaderProtection() &&
4188 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4189 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4190 RaiseError(QUIC_ENCRYPTION_FAILURE);
4191 return 0;
4192 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004193
4194 return ad_len + output_length;
4195}
4196
nharper55fa6132019-05-07 19:37:21 -07004197namespace {
4198
4199const size_t kHPSampleLen = 16;
4200
4201constexpr bool IsLongHeader(uint8_t type_byte) {
4202 return (type_byte & FLAGS_LONG_HEADER) != 0;
4203}
4204
4205} // namespace
4206
4207bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4208 char* buffer,
4209 size_t buffer_len,
4210 size_t ad_len) {
4211 QuicDataReader buffer_reader(buffer, buffer_len);
4212 QuicDataWriter buffer_writer(buffer_len, buffer);
4213 // The sample starts 4 bytes after the start of the packet number.
4214 if (ad_len < last_written_packet_number_length_) {
4215 return false;
4216 }
4217 size_t pn_offset = ad_len - last_written_packet_number_length_;
4218 // Sample the ciphertext and generate the mask to use for header protection.
4219 size_t sample_offset = pn_offset + 4;
4220 QuicDataReader sample_reader(buffer, buffer_len);
dmcardlecf0bfcf2019-12-13 08:08:21 -08004221 quiche::QuicheStringPiece sample;
nharper55fa6132019-05-07 19:37:21 -07004222 if (!sample_reader.Seek(sample_offset) ||
4223 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4224 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4225 << ", sample len: " << kHPSampleLen
4226 << ", buffer len: " << buffer_len;
4227 return false;
4228 }
4229
4230 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4231 if (mask.empty()) {
4232 QUIC_BUG << "Unable to generate header protection mask.";
4233 return false;
4234 }
4235 QuicDataReader mask_reader(mask.data(), mask.size());
4236
4237 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4238 uint8_t bitmask = 0x1f;
4239 uint8_t type_byte;
4240 if (!buffer_reader.ReadUInt8(&type_byte)) {
4241 return false;
4242 }
4243 QuicLongHeaderType header_type;
4244 if (IsLongHeader(type_byte)) {
4245 bitmask = 0x0f;
fayang36825da2019-08-21 14:01:27 -07004246 if (!GetLongHeaderType(type_byte, &header_type)) {
nharper55fa6132019-05-07 19:37:21 -07004247 return false;
4248 }
4249 }
4250 uint8_t mask_byte;
4251 if (!mask_reader.ReadUInt8(&mask_byte) ||
4252 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4253 return false;
4254 }
4255
4256 // Adjust |pn_offset| to account for the diversification nonce.
4257 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4258 perspective_ == Perspective::IS_SERVER &&
4259 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4260 if (pn_offset <= kDiversificationNonceSize) {
4261 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4262 return false;
4263 }
4264 pn_offset -= kDiversificationNonceSize;
4265 }
4266 // Advance the reader and writer to the packet number. Both the reader and
4267 // writer have each read/written one byte.
4268 if (!buffer_writer.Seek(pn_offset - 1) ||
4269 !buffer_reader.Seek(pn_offset - 1)) {
4270 return false;
4271 }
4272 // Apply the rest of the mask to the packet number.
4273 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4274 uint8_t buffer_byte;
4275 uint8_t mask_byte;
4276 if (!mask_reader.ReadUInt8(&mask_byte) ||
4277 !buffer_reader.ReadUInt8(&buffer_byte) ||
4278 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4279 return false;
4280 }
4281 }
4282 return true;
4283}
4284
4285bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4286 const QuicEncryptedPacket& packet,
4287 QuicPacketHeader* header,
4288 uint64_t* full_packet_number,
4289 std::vector<char>* associated_data) {
4290 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4291 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4292 if (decrypter == nullptr) {
4293 QUIC_DVLOG(1)
dschinazi4b5a68a2019-08-15 15:45:36 -07004294 << ENDPOINT
nharper55fa6132019-05-07 19:37:21 -07004295 << "No decrypter available for removing header protection at level "
dschinazief79a5f2019-10-04 10:32:54 -07004296 << EncryptionLevelToString(expected_decryption_level);
nharper55fa6132019-05-07 19:37:21 -07004297 return false;
4298 }
4299
4300 bool has_diversification_nonce =
4301 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4302 header->long_packet_type == ZERO_RTT_PROTECTED &&
4303 perspective_ == Perspective::IS_CLIENT &&
4304 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4305
4306 // Read a sample from the ciphertext and compute the mask to use for header
4307 // protection.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004308 quiche::QuicheStringPiece remaining_packet = reader->PeekRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07004309 QuicDataReader sample_reader(remaining_packet);
4310
4311 // The sample starts 4 bytes after the start of the packet number.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004312 quiche::QuicheStringPiece pn;
nharper55fa6132019-05-07 19:37:21 -07004313 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4314 QUIC_DVLOG(1) << "Not enough data to sample";
4315 return false;
4316 }
4317 if (has_diversification_nonce) {
4318 // In Google QUIC, the diversification nonce comes between the packet number
4319 // and the sample.
4320 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4321 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4322 return false;
4323 }
4324 }
4325 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4326 QuicDataReader mask_reader(mask.data(), mask.size());
4327 if (mask.empty()) {
4328 QUIC_DVLOG(1) << "Failed to compute mask";
4329 return false;
4330 }
4331
4332 // Unmask the rest of the type byte.
4333 uint8_t bitmask = 0x1f;
4334 if (IsLongHeader(header->type_byte)) {
4335 bitmask = 0x0f;
4336 }
4337 uint8_t mask_byte;
4338 if (!mask_reader.ReadUInt8(&mask_byte)) {
4339 QUIC_DVLOG(1) << "No first byte to read from mask";
4340 return false;
4341 }
4342 header->type_byte ^= (mask_byte & bitmask);
4343
4344 // Compute the packet number length.
4345 header->packet_number_length =
4346 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4347
4348 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
bnc4e9283d2019-12-17 07:08:57 -08004349 QuicDataWriter pn_writer(QUICHE_ARRAYSIZE(pn_buffer), pn_buffer);
nharper55fa6132019-05-07 19:37:21 -07004350
4351 // Read the (protected) packet number from the reader and unmask the packet
4352 // number.
4353 for (size_t i = 0; i < header->packet_number_length; ++i) {
4354 uint8_t protected_pn_byte, mask_byte;
4355 if (!mask_reader.ReadUInt8(&mask_byte) ||
4356 !reader->ReadUInt8(&protected_pn_byte) ||
4357 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4358 QUIC_DVLOG(1) << "Failed to unmask packet number";
4359 return false;
4360 }
4361 }
4362 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4363 QuicPacketNumber base_packet_number;
4364 if (supports_multiple_packet_number_spaces_) {
4365 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4366 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4367 return false;
4368 }
4369 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4370 } else {
4371 base_packet_number = largest_packet_number_;
4372 }
4373 if (!ProcessAndCalculatePacketNumber(
4374 &packet_number_reader, header->packet_number_length,
4375 base_packet_number, full_packet_number)) {
4376 return false;
4377 }
4378
4379 // Get the associated data, and apply the same unmasking operations to it.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004380 quiche::QuicheStringPiece ad = GetAssociatedDataFromEncryptedPacket(
nharper55fa6132019-05-07 19:37:21 -07004381 version_.transport_version, packet,
4382 GetIncludedDestinationConnectionIdLength(*header),
4383 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4384 has_diversification_nonce, header->packet_number_length,
4385 header->retry_token_length_length, header->retry_token.length(),
4386 header->length_length);
4387 *associated_data = std::vector<char>(ad.begin(), ad.end());
4388 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4389
4390 // Apply the unmasked type byte and packet number to |associated_data|.
4391 if (!ad_writer.WriteUInt8(header->type_byte)) {
4392 return false;
4393 }
4394 // Put the packet number at the end of the AD, or if there's a diversification
4395 // nonce, before that (which is at the end of the AD).
4396 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4397 if (has_diversification_nonce) {
4398 seek_len -= kDiversificationNonceSize;
4399 }
4400 if (!ad_writer.Seek(seek_len) ||
4401 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4402 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4403 return false;
4404 }
4405
4406 return true;
4407}
4408
QUICHE teama6ef0a62019-03-07 20:34:33 -05004409size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4410 QuicPacketNumber packet_number,
4411 const QuicPacket& packet,
4412 char* buffer,
4413 size_t buffer_len) {
4414 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004415 if (encrypter_[level] == nullptr) {
4416 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004417 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004418 RaiseError(QUIC_ENCRYPTION_FAILURE);
4419 return 0;
4420 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004421
dmcardlecf0bfcf2019-12-13 08:08:21 -08004422 quiche::QuicheStringPiece associated_data =
QUICHE teama6ef0a62019-03-07 20:34:33 -05004423 packet.AssociatedData(version_.transport_version);
4424 // Copy in the header, because the encrypter only populates the encrypted
4425 // plaintext content.
4426 const size_t ad_len = associated_data.length();
4427 memmove(buffer, associated_data.data(), ad_len);
4428 // Encrypt the plaintext into the buffer.
4429 size_t output_length = 0;
4430 if (!encrypter_[level]->EncryptPacket(
4431 packet_number.ToUint64(), associated_data,
4432 packet.Plaintext(version_.transport_version), buffer + ad_len,
4433 &output_length, buffer_len - ad_len)) {
4434 RaiseError(QUIC_ENCRYPTION_FAILURE);
4435 return 0;
4436 }
nharper55fa6132019-05-07 19:37:21 -07004437 if (version_.HasHeaderProtection() &&
4438 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4439 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4440 RaiseError(QUIC_ENCRYPTION_FAILURE);
4441 return 0;
4442 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004443
4444 return ad_len + output_length;
4445}
4446
4447size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4448 size_t plaintext_size) const {
4449 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4450}
4451
4452size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4453 // In order to keep the code simple, we don't have the current encryption
4454 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4455 size_t min_plaintext_size = ciphertext_size;
4456
QUICHE team6987b4a2019-03-15 16:23:04 -07004457 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004458 if (encrypter_[i] != nullptr) {
4459 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4460 if (size < min_plaintext_size) {
4461 min_plaintext_size = size;
4462 }
4463 }
4464 }
4465
4466 return min_plaintext_size;
4467}
4468
dmcardlecf0bfcf2019-12-13 08:08:21 -08004469bool QuicFramer::DecryptPayload(quiche::QuicheStringPiece encrypted,
4470 quiche::QuicheStringPiece associated_data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004471 const QuicPacketHeader& header,
4472 char* decrypted_buffer,
4473 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004474 size_t* decrypted_length,
4475 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004476 if (!EncryptionLevelIsValid(decrypter_level_)) {
4477 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4478 return false;
4479 }
zhongyi546cc452019-04-12 15:27:49 -07004480 EncryptionLevel level = decrypter_level_;
4481 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004482 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004483 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004484 if (header.form == GOOGLE_QUIC_PACKET) {
4485 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4486 "knows which decrypter to use";
4487 return false;
4488 }
zhongyi546cc452019-04-12 15:27:49 -07004489 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004490 if (!EncryptionLevelIsValid(level)) {
4491 QUIC_BUG << "Attempted to decrypt with bad level";
4492 return false;
4493 }
zhongyi546cc452019-04-12 15:27:49 -07004494 decrypter = decrypter_[level].get();
4495 if (decrypter == nullptr) {
4496 return false;
4497 }
4498 if (level == ENCRYPTION_ZERO_RTT &&
4499 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4500 decrypter->SetDiversificationNonce(*header.nonce);
4501 }
4502 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004503 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4504 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4505 return false;
4506 }
QUICHE team76086e42019-03-25 15:12:29 -07004507 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4508 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004509
nharper855d2172019-05-02 16:17:46 -07004510 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004511 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4512 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004513 return false;
4514 }
zhongyi546cc452019-04-12 15:27:49 -07004515
4516 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004517 header.packet_number.ToUint64(), associated_data, encrypted,
4518 decrypted_buffer, decrypted_length, buffer_length);
4519 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004520 visitor_->OnDecryptedPacket(level);
4521 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004522 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004523 if (header.nonce != nullptr) {
4524 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004525 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004526 }
4527 bool try_alternative_decryption = true;
4528 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4529 if (perspective_ == Perspective::IS_CLIENT) {
4530 if (header.nonce == nullptr) {
4531 // Can not use INITIAL decryption without a diversification nonce.
4532 try_alternative_decryption = false;
4533 }
4534 } else {
4535 DCHECK(header.nonce == nullptr);
4536 }
4537 }
4538
4539 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004540 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004541 header.packet_number.ToUint64(), associated_data, encrypted,
4542 decrypted_buffer, decrypted_length, buffer_length);
4543 }
4544 if (success) {
4545 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004546 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004547 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004548 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4549 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4550 "alternative_decrypter_level_";
4551 return false;
4552 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004553 // Switch to the alternative decrypter and latch so that we cannot
4554 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004555 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004556 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004557 } else {
4558 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004559 EncryptionLevel level = alternative_decrypter_level_;
4560 alternative_decrypter_level_ = decrypter_level_;
4561 decrypter_level_ = level;
4562 }
4563 }
4564 }
4565
4566 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004567 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004568 return false;
4569 }
4570
4571 return true;
4572}
4573
4574size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4575 // Type byte, largest_acked, and delay_time are straight-forward.
4576 size_t ack_frame_size = kQuicFrameTypeSize;
4577 QuicPacketNumber largest_acked = LargestAcked(frame);
4578 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4579 uint64_t ack_delay_time_us;
4580 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004581 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004582 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4583
4584 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4585 // then the ecn counters are included...
4586 if (frame.ecn_counters_populated &&
4587 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4588 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4589 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4590 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4591 }
4592
4593 // The rest (ack_block_count, first_ack_block, and additional ack
4594 // blocks, if any) depends:
4595 uint64_t ack_block_count = frame.packets.NumIntervals();
4596 if (ack_block_count == 0) {
4597 // If the QuicAckFrame has no Intervals, then it is interpreted
4598 // as an ack of a single packet at QuicAckFrame.largest_acked.
4599 // The resulting ack will consist of only the frame's
4600 // largest_ack & first_ack_block fields. The first ack block will be 0
4601 // (indicating a single packet) and the ack block_count will be 0.
4602 // Each 0 takes 1 byte when VarInt62 encoded.
4603 ack_frame_size += 2;
4604 return ack_frame_size;
4605 }
4606
4607 auto itr = frame.packets.rbegin();
4608 QuicPacketNumber ack_block_largest = largest_acked;
4609 QuicPacketNumber ack_block_smallest;
4610 if ((itr->max() - 1) == largest_acked) {
4611 // If largest_acked + 1 is equal to the Max() of the first Interval
4612 // in the QuicAckFrame then the first Interval is the first ack block of the
4613 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4614 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4615 // the remaining Intervals are encoded in additional ack blocks in the
4616 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4617 // Intervals - 1.
4618 ack_block_smallest = itr->min();
4619 itr++;
4620 ack_block_count--;
4621 } else {
4622 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4623 // the first Interval then it is interpreted as acking a single
4624 // packet at QuicAckFrame.largest_acked, with additional
4625 // Intervals indicating additional ack blocks. The encoding is
4626 // a) The packet's largest_acked is the QuicAckFrame's largest
4627 // acked,
4628 // b) the first ack block size is 0,
4629 // c) The packet's ack_block_count is the number of QuicAckFrame
4630 // Intervals, and
4631 // d) The QuicAckFrame Intervals are encoded in additional ack
4632 // blocks in the packet.
4633 ack_block_smallest = largest_acked;
4634 }
4635 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4636 ack_frame_size += ack_block_count_size;
4637
4638 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4639 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4640 ack_frame_size += first_ack_block_size;
4641
4642 // Account for the remaining Intervals, if any.
4643 while (ack_block_count != 0) {
4644 uint64_t gap_size = ack_block_smallest - itr->max();
4645 // Decrement per the protocol specification
4646 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4647 ack_frame_size += size_of_gap_size;
4648
4649 uint64_t block_size = itr->max() - itr->min();
4650 // Decrement per the protocol specification
4651 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4652 ack_frame_size += size_of_block_size;
4653
4654 ack_block_smallest = itr->min();
4655 itr++;
4656 ack_block_count--;
4657 }
4658
4659 return ack_frame_size;
4660}
4661
4662size_t QuicFramer::GetAckFrameSize(
4663 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004664 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004665 DCHECK(!ack.packets.Empty());
4666 size_t ack_size = 0;
4667
fkastenholz305e1732019-06-18 05:01:22 -07004668 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004669 return GetIetfAckFrameSize(ack);
4670 }
4671 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4672 QuicPacketNumberLength largest_acked_length =
renjietang488201d2019-12-17 13:40:49 -08004673 GetMinPacketNumberLength(LargestAcked(ack));
4674 QuicPacketNumberLength ack_block_length =
4675 GetMinPacketNumberLength(QuicPacketNumber(ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004676
4677 ack_size =
4678 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4679 // First ack block length.
4680 ack_size += ack_block_length;
4681 if (ack_info.num_ack_blocks != 0) {
4682 ack_size += kNumberOfAckBlocksSize;
4683 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4684 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4685 }
4686
4687 // Include timestamps.
4688 if (process_timestamps_) {
4689 ack_size += GetAckFrameTimeStampSize(ack);
4690 }
4691
4692 return ack_size;
4693}
4694
4695size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4696 if (ack.received_packet_times.empty()) {
4697 return 0;
4698 }
4699
4700 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4701 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4702 (ack.received_packet_times.size() - 1);
4703}
4704
4705size_t QuicFramer::ComputeFrameLength(
4706 const QuicFrame& frame,
4707 bool last_frame_in_packet,
4708 QuicPacketNumberLength packet_number_length) {
4709 switch (frame.type) {
4710 case STREAM_FRAME:
4711 return GetMinStreamFrameSize(
4712 version_.transport_version, frame.stream_frame.stream_id,
4713 frame.stream_frame.offset, last_frame_in_packet,
4714 frame.stream_frame.data_length) +
4715 frame.stream_frame.data_length;
4716 case CRYPTO_FRAME:
4717 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4718 frame.crypto_frame->data_length) +
4719 frame.crypto_frame->data_length;
4720 case ACK_FRAME: {
4721 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4722 }
4723 case STOP_WAITING_FRAME:
renjietang488201d2019-12-17 13:40:49 -08004724 return GetStopWaitingFrameSize(packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004725 case MTU_DISCOVERY_FRAME:
4726 // MTU discovery frames are serialized as ping frames.
4727 return kQuicFrameTypeSize;
4728 case MESSAGE_FRAME:
4729 return GetMessageFrameSize(version_.transport_version,
4730 last_frame_in_packet,
4731 frame.message_frame->message_length);
4732 case PADDING_FRAME:
4733 DCHECK(false);
4734 return 0;
4735 default:
4736 return GetRetransmittableControlFrameSize(version_.transport_version,
4737 frame);
4738 }
4739}
4740
4741bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4742 bool last_frame_in_packet,
4743 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004744 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004745 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4746 }
4747 uint8_t type_byte = 0;
4748 switch (frame.type) {
4749 case STREAM_FRAME:
4750 type_byte =
4751 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4752 break;
4753 case ACK_FRAME:
4754 return true;
4755 case MTU_DISCOVERY_FRAME:
4756 type_byte = static_cast<uint8_t>(PING_FRAME);
4757 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004758 case NEW_CONNECTION_ID_FRAME:
4759 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004760 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004761 return RaiseError(QUIC_INTERNAL_ERROR);
4762 case RETIRE_CONNECTION_ID_FRAME:
4763 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004764 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004765 return RaiseError(QUIC_INTERNAL_ERROR);
4766 case NEW_TOKEN_FRAME:
4767 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004768 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004769 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004770 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004771 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004772 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004773 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004774 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004775 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004776 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004777 return RaiseError(QUIC_INTERNAL_ERROR);
4778 case PATH_RESPONSE_FRAME:
4779 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004780 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004781 return RaiseError(QUIC_INTERNAL_ERROR);
4782 case PATH_CHALLENGE_FRAME:
4783 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004784 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004785 return RaiseError(QUIC_INTERNAL_ERROR);
4786 case STOP_SENDING_FRAME:
4787 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004788 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004789 return RaiseError(QUIC_INTERNAL_ERROR);
4790 case MESSAGE_FRAME:
4791 return true;
4792
4793 default:
4794 type_byte = static_cast<uint8_t>(frame.type);
4795 break;
4796 }
4797
4798 return writer->WriteUInt8(type_byte);
4799}
4800
4801bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4802 bool last_frame_in_packet,
4803 QuicDataWriter* writer) {
4804 uint8_t type_byte = 0;
4805 switch (frame.type) {
4806 case PADDING_FRAME:
4807 type_byte = IETF_PADDING;
4808 break;
4809 case RST_STREAM_FRAME:
4810 type_byte = IETF_RST_STREAM;
4811 break;
4812 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004813 switch (frame.connection_close_frame->close_type) {
4814 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4815 type_byte = IETF_APPLICATION_CLOSE;
4816 break;
4817 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4818 type_byte = IETF_CONNECTION_CLOSE;
4819 break;
4820 default:
4821 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4822 return RaiseError(QUIC_INTERNAL_ERROR);
4823 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004824 break;
4825 case GOAWAY_FRAME:
4826 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004827 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004828 return RaiseError(QUIC_INTERNAL_ERROR);
4829 case WINDOW_UPDATE_FRAME:
4830 // Depending on whether there is a stream ID or not, will be either a
4831 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4832 if (frame.window_update_frame->stream_id ==
4833 QuicUtils::GetInvalidStreamId(transport_version())) {
4834 type_byte = IETF_MAX_DATA;
4835 } else {
4836 type_byte = IETF_MAX_STREAM_DATA;
4837 }
4838 break;
4839 case BLOCKED_FRAME:
4840 if (frame.blocked_frame->stream_id ==
4841 QuicUtils::GetInvalidStreamId(transport_version())) {
ianswett2f077442019-12-12 11:51:24 -08004842 type_byte = IETF_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004843 } else {
ianswett2f077442019-12-12 11:51:24 -08004844 type_byte = IETF_STREAM_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004845 }
4846 break;
4847 case STOP_WAITING_FRAME:
4848 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004849 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004850 return RaiseError(QUIC_INTERNAL_ERROR);
4851 case PING_FRAME:
4852 type_byte = IETF_PING;
4853 break;
4854 case STREAM_FRAME:
4855 type_byte =
4856 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4857 break;
4858 case ACK_FRAME:
4859 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4860 // in the buffer.
4861 return true;
4862 case MTU_DISCOVERY_FRAME:
4863 // The path MTU discovery frame is encoded as a PING frame on the wire.
4864 type_byte = IETF_PING;
4865 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004866 case NEW_CONNECTION_ID_FRAME:
4867 type_byte = IETF_NEW_CONNECTION_ID;
4868 break;
4869 case RETIRE_CONNECTION_ID_FRAME:
4870 type_byte = IETF_RETIRE_CONNECTION_ID;
4871 break;
4872 case NEW_TOKEN_FRAME:
4873 type_byte = IETF_NEW_TOKEN;
4874 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004875 case MAX_STREAMS_FRAME:
4876 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004877 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004878 } else {
4879 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004880 }
4881 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004882 case STREAMS_BLOCKED_FRAME:
4883 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004884 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004885 } else {
4886 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004887 }
4888 break;
4889 case PATH_RESPONSE_FRAME:
4890 type_byte = IETF_PATH_RESPONSE;
4891 break;
4892 case PATH_CHALLENGE_FRAME:
4893 type_byte = IETF_PATH_CHALLENGE;
4894 break;
4895 case STOP_SENDING_FRAME:
4896 type_byte = IETF_STOP_SENDING;
4897 break;
4898 case MESSAGE_FRAME:
4899 return true;
4900 case CRYPTO_FRAME:
4901 type_byte = IETF_CRYPTO;
4902 break;
fayang01062942020-01-22 07:23:23 -08004903 case HANDSHAKE_DONE_FRAME:
4904 type_byte = IETF_HANDSHAKE_DONE;
4905 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004906 default:
4907 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4908 << frame.type;
4909 return false;
4910 }
4911 return writer->WriteUInt8(type_byte);
4912}
4913
4914// static
4915bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4916 QuicPacketNumber packet_number,
4917 QuicDataWriter* writer) {
4918 DCHECK(packet_number.IsInitialized());
4919 if (!IsValidPacketNumberLength(packet_number_length)) {
4920 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4921 return false;
4922 }
4923 return writer->WriteBytesToUInt64(packet_number_length,
4924 packet_number.ToUint64());
4925}
4926
4927// static
4928bool QuicFramer::AppendStreamId(size_t stream_id_length,
4929 QuicStreamId stream_id,
4930 QuicDataWriter* writer) {
4931 if (stream_id_length == 0 || stream_id_length > 4) {
4932 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4933 return false;
4934 }
4935 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4936}
4937
4938// static
4939bool QuicFramer::AppendStreamOffset(size_t offset_length,
4940 QuicStreamOffset offset,
4941 QuicDataWriter* writer) {
4942 if (offset_length == 1 || offset_length > 8) {
4943 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4944 return false;
4945 }
4946
4947 return writer->WriteBytesToUInt64(offset_length, offset);
4948}
4949
4950// static
4951bool QuicFramer::AppendAckBlock(uint8_t gap,
4952 QuicPacketNumberLength length_length,
4953 uint64_t length,
4954 QuicDataWriter* writer) {
4955 if (length == 0) {
4956 if (!IsValidPacketNumberLength(length_length)) {
4957 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4958 return false;
4959 }
4960 return writer->WriteUInt8(gap) &&
4961 writer->WriteBytesToUInt64(length_length, length);
4962 }
4963 return writer->WriteUInt8(gap) &&
4964 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4965}
4966
4967bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4968 bool no_stream_frame_length,
4969 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004970 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004971 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4972 }
4973 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4974 writer)) {
4975 QUIC_BUG << "Writing stream id size failed.";
4976 return false;
4977 }
renjietang488201d2019-12-17 13:40:49 -08004978 if (!AppendStreamOffset(GetStreamOffsetSize(frame.offset), frame.offset,
4979 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004980 QUIC_BUG << "Writing offset size failed.";
4981 return false;
4982 }
4983 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07004984 static_assert(
wubeff50282019-06-19 09:04:30 -07004985 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07004986 std::numeric_limits<uint16_t>::max(),
4987 "If frame.data_length can hold more than a uint16_t than we need to "
4988 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
4989 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004990 QUIC_BUG << "Writing stream frame length failed";
4991 return false;
4992 }
4993 }
4994
4995 if (data_producer_ != nullptr) {
4996 DCHECK_EQ(nullptr, frame.data_buffer);
4997 if (frame.data_length == 0) {
4998 return true;
4999 }
5000 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5001 frame.data_length,
5002 writer) != WRITE_SUCCESS) {
5003 QUIC_BUG << "Writing frame data failed.";
5004 return false;
5005 }
5006 return true;
5007 }
5008
5009 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5010 QUIC_BUG << "Writing frame data failed.";
5011 return false;
5012 }
5013 return true;
5014}
5015
QUICHE teama6ef0a62019-03-07 20:34:33 -05005016bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5017 QuicDataWriter* writer) {
5018 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5019 set_detailed_error("Writing token length failed.");
5020 return false;
5021 }
5022 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5023 set_detailed_error("Writing token buffer failed.");
5024 return false;
5025 }
5026 return true;
5027}
5028
5029bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5030 QuicNewTokenFrame* frame) {
5031 uint64_t length;
5032 if (!reader->ReadVarInt62(&length)) {
5033 set_detailed_error("Unable to read new token length.");
5034 return false;
5035 }
5036 if (length > kMaxNewTokenTokenLength) {
5037 set_detailed_error("Token length larger than maximum.");
5038 return false;
5039 }
5040
dmcardlecf0bfcf2019-12-13 08:08:21 -08005041 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
5042 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005043 if (!reader->ReadStringPiece(&data, length)) {
5044 set_detailed_error("Unable to read new token data.");
5045 return false;
5046 }
vasilvvc48c8712019-03-11 13:38:16 -07005047 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005048 return true;
5049}
5050
5051// Add a new ietf-format stream frame.
5052// Bits controlling whether there is a frame-length and frame-offset
5053// are in the QuicStreamFrame.
5054bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5055 bool last_frame_in_packet,
5056 QuicDataWriter* writer) {
5057 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5058 set_detailed_error("Writing stream id failed.");
5059 return false;
5060 }
5061
5062 if (frame.offset != 0) {
5063 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5064 set_detailed_error("Writing data offset failed.");
5065 return false;
5066 }
5067 }
5068
5069 if (!last_frame_in_packet) {
5070 if (!writer->WriteVarInt62(frame.data_length)) {
5071 set_detailed_error("Writing data length failed.");
5072 return false;
5073 }
5074 }
5075
5076 if (frame.data_length == 0) {
5077 return true;
5078 }
5079 if (data_producer_ == nullptr) {
5080 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5081 set_detailed_error("Writing frame data failed.");
5082 return false;
5083 }
5084 } else {
5085 DCHECK_EQ(nullptr, frame.data_buffer);
5086
5087 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5088 frame.data_length,
5089 writer) != WRITE_SUCCESS) {
5090 set_detailed_error("Writing frame data failed.");
5091 return false;
5092 }
5093 }
5094 return true;
5095}
5096
5097bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5098 QuicDataWriter* writer) {
5099 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5100 set_detailed_error("Writing data offset failed.");
5101 return false;
5102 }
5103 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5104 set_detailed_error("Writing data length failed.");
5105 return false;
5106 }
5107 if (data_producer_ == nullptr) {
5108 if (frame.data_buffer == nullptr ||
5109 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5110 set_detailed_error("Writing frame data failed.");
5111 return false;
5112 }
5113 } else {
5114 DCHECK_EQ(nullptr, frame.data_buffer);
5115 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5116 frame.data_length, writer)) {
5117 return false;
5118 }
5119 }
5120 return true;
5121}
5122
5123void QuicFramer::set_version(const ParsedQuicVersion version) {
5124 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5125 version_ = version;
5126}
5127
5128bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5129 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005130 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005131 return AppendIetfAckFrameAndTypeByte(frame, writer);
5132 }
5133
5134 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5135 QuicPacketNumber largest_acked = LargestAcked(frame);
5136 QuicPacketNumberLength largest_acked_length =
renjietang488201d2019-12-17 13:40:49 -08005137 GetMinPacketNumberLength(largest_acked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005138 QuicPacketNumberLength ack_block_length =
renjietang488201d2019-12-17 13:40:49 -08005139 GetMinPacketNumberLength(QuicPacketNumber(new_ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005140 // Calculate available bytes for timestamps and ack blocks.
5141 int32_t available_timestamp_and_ack_block_bytes =
5142 writer->capacity() - writer->length() - ack_block_length -
5143 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5144 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5145 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5146
5147 // Write out the type byte by setting the low order bits and doing shifts
5148 // to make room for the next bit flags to be set.
5149 // Whether there are multiple ack blocks.
5150 uint8_t type_byte = 0;
5151 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5152 kQuicHasMultipleAckBlocksOffset);
5153
5154 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5155 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5156
5157 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5158 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5159
5160 type_byte |= kQuicFrameTypeAckMask;
5161
5162 if (!writer->WriteUInt8(type_byte)) {
5163 return false;
5164 }
5165
5166 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5167 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5168
5169 // Number of ack blocks.
5170 size_t num_ack_blocks =
5171 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5172 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5173 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5174 }
5175
5176 // Largest acked.
5177 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5178 return false;
5179 }
5180
5181 // Largest acked delta time.
5182 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5183 if (!frame.ack_delay_time.IsInfinite()) {
5184 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5185 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5186 }
5187 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5188 return false;
5189 }
5190
5191 if (num_ack_blocks > 0) {
5192 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5193 return false;
5194 }
5195 }
5196
5197 // First ack block length.
5198 if (!AppendPacketNumber(ack_block_length,
5199 QuicPacketNumber(new_ack_info.first_block_length),
5200 writer)) {
5201 return false;
5202 }
5203
5204 // Ack blocks.
5205 if (num_ack_blocks > 0) {
5206 size_t num_ack_blocks_written = 0;
5207 // Append, in descending order from the largest ACKed packet, a series of
5208 // ACK blocks that represents the successfully acknoweldged packets. Each
5209 // appended gap/block length represents a descending delta from the previous
5210 // block. i.e.:
5211 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5212 // For gaps larger than can be represented by a single encoded gap, a 0
5213 // length gap of the maximum is used, i.e.:
5214 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5215 auto itr = frame.packets.rbegin();
5216 QuicPacketNumber previous_start = itr->min();
5217 ++itr;
5218
5219 for (;
5220 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5221 previous_start = itr->min(), ++itr) {
5222 const auto& interval = *itr;
5223 const uint64_t total_gap = previous_start - interval.max();
5224 const size_t num_encoded_gaps =
5225 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5226 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005227
5228 // Append empty ACK blocks because the gap is longer than a single gap.
5229 for (size_t i = 1;
5230 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5231 ++i) {
5232 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5233 ack_block_length, 0, writer)) {
5234 return false;
5235 }
5236 ++num_ack_blocks_written;
5237 }
5238 if (num_ack_blocks_written >= num_ack_blocks) {
5239 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5240 QUIC_BUG << "Wrote " << num_ack_blocks_written
5241 << ", expected to write " << num_ack_blocks;
5242 }
5243 break;
5244 }
5245
5246 const uint8_t last_gap =
5247 total_gap -
5248 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5249 // Append the final ACK block with a non-empty size.
wub13d75452019-11-05 07:24:56 -08005250 if (!AppendAckBlock(last_gap, ack_block_length, interval.Length(),
5251 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005252 return false;
5253 }
5254 ++num_ack_blocks_written;
5255 }
5256 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5257 }
5258 // Timestamps.
5259 // If we don't process timestamps or if we don't have enough available space
5260 // to append all the timestamps, don't append any of them.
5261 if (process_timestamps_ && writer->capacity() - writer->length() >=
5262 GetAckFrameTimeStampSize(frame)) {
5263 if (!AppendTimestampsToAckFrame(frame, writer)) {
5264 return false;
5265 }
5266 } else {
5267 uint8_t num_received_packets = 0;
5268 if (!writer->WriteBytes(&num_received_packets, 1)) {
5269 return false;
5270 }
5271 }
5272
5273 return true;
5274}
5275
5276bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5277 QuicDataWriter* writer) {
5278 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5279 frame.received_packet_times.size());
5280 // num_received_packets is only 1 byte.
5281 if (frame.received_packet_times.size() >
5282 std::numeric_limits<uint8_t>::max()) {
5283 return false;
5284 }
5285
5286 uint8_t num_received_packets = frame.received_packet_times.size();
5287 if (!writer->WriteBytes(&num_received_packets, 1)) {
5288 return false;
5289 }
5290 if (num_received_packets == 0) {
5291 return true;
5292 }
5293
5294 auto it = frame.received_packet_times.begin();
5295 QuicPacketNumber packet_number = it->first;
5296 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5297
5298 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5299 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5300 return false;
5301 }
5302
5303 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5304 return false;
5305 }
5306
5307 // Use the lowest 4 bytes of the time delta from the creation_time_.
5308 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5309 uint32_t time_delta_us =
5310 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5311 (time_epoch_delta_us - 1));
5312 if (!writer->WriteUInt32(time_delta_us)) {
5313 return false;
5314 }
5315
5316 QuicTime prev_time = it->second;
5317
5318 for (++it; it != frame.received_packet_times.end(); ++it) {
5319 packet_number = it->first;
5320 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5321
5322 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5323 return false;
5324 }
5325
5326 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5327 return false;
5328 }
5329
5330 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5331 prev_time = it->second;
5332 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5333 return false;
5334 }
5335 }
5336 return true;
5337}
5338
5339bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5340 const QuicStopWaitingFrame& frame,
5341 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005342 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
bncbe885272020-01-16 11:10:48 -08005343 DCHECK(frame.least_unacked.IsInitialized());
5344 DCHECK_GE(header.packet_number, frame.least_unacked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005345 const uint64_t least_unacked_delta =
5346 header.packet_number - frame.least_unacked;
5347 const uint64_t length_shift = header.packet_number_length * 8;
5348
5349 if (least_unacked_delta >> length_shift > 0) {
5350 QUIC_BUG << "packet_number_length " << header.packet_number_length
5351 << " is too small for least_unacked_delta: " << least_unacked_delta
5352 << " packet_number:" << header.packet_number
5353 << " least_unacked:" << frame.least_unacked
5354 << " version:" << version_.transport_version;
5355 return false;
5356 }
5357 if (least_unacked_delta == 0) {
5358 return writer->WriteBytesToUInt64(header.packet_number_length,
5359 least_unacked_delta);
5360 }
5361 if (!AppendPacketNumber(header.packet_number_length,
5362 QuicPacketNumber(least_unacked_delta), writer)) {
5363 QUIC_BUG << " seq failed: " << header.packet_number_length;
5364 return false;
5365 }
5366
5367 return true;
5368}
5369
5370int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005371 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005372 size_t available_space) {
5373 // Number of blocks requested in the frame
5374 uint64_t ack_block_count = frame.packets.NumIntervals();
5375
5376 auto itr = frame.packets.rbegin();
5377
5378 int actual_block_count = 1;
5379 uint64_t block_length = itr->max() - itr->min();
5380 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5381 if (encoded_size > available_space) {
5382 return 0;
5383 }
5384 available_space -= encoded_size;
5385 QuicPacketNumber previous_ack_end = itr->min();
5386 ack_block_count--;
5387
5388 while (ack_block_count) {
5389 // Each block is a gap followed by another ACK. Calculate each value,
5390 // determine the encoded lengths, and check against the available space.
5391 itr++;
5392 size_t gap = previous_ack_end - itr->max() - 1;
5393 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5394
5395 // Add the ACK block.
5396 block_length = itr->max() - itr->min();
5397 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5398
5399 if (encoded_size > available_space) {
5400 // No room for this block, so what we've
5401 // done up to now is all that can be done.
5402 return actual_block_count;
5403 }
5404 available_space -= encoded_size;
5405 actual_block_count++;
5406 previous_ack_end = itr->min();
5407 ack_block_count--;
5408 }
5409 // Ran through the whole thing! We can do all blocks.
5410 return actual_block_count;
5411}
5412
5413bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5414 QuicDataWriter* writer) {
5415 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5416 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5417 uint8_t type = IETF_ACK;
5418 if (frame.ecn_counters_populated &&
5419 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5420 type = IETF_ACK_ECN;
5421 }
5422
5423 if (!writer->WriteUInt8(type)) {
5424 set_detailed_error("No room for frame-type");
5425 return false;
5426 }
5427
5428 QuicPacketNumber largest_acked = LargestAcked(frame);
5429 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5430 set_detailed_error("No room for largest-acked in ack frame");
5431 return false;
5432 }
5433
5434 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5435 if (!frame.ack_delay_time.IsInfinite()) {
5436 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5437 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005438 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005439 }
5440
5441 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5442 set_detailed_error("No room for ack-delay in ack frame");
5443 return false;
5444 }
5445 if (type == IETF_ACK_ECN) {
5446 // Encode the ACK ECN fields
5447 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5448 set_detailed_error("No room for ect_0_count in ack frame");
5449 return false;
5450 }
5451 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5452 set_detailed_error("No room for ect_1_count in ack frame");
5453 return false;
5454 }
5455 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5456 set_detailed_error("No room for ecn_ce_count in ack frame");
5457 return false;
5458 }
5459 }
5460
5461 uint64_t ack_block_count = frame.packets.NumIntervals();
5462 if (ack_block_count == 0) {
5463 // If the QuicAckFrame has no Intervals, then it is interpreted
5464 // as an ack of a single packet at QuicAckFrame.largest_acked.
5465 // The resulting ack will consist of only the frame's
5466 // largest_ack & first_ack_block fields. The first ack block will be 0
5467 // (indicating a single packet) and the ack block_count will be 0.
5468 if (!writer->WriteVarInt62(0)) {
5469 set_detailed_error("No room for ack block count in ack frame");
5470 return false;
5471 }
5472 // size of the first block is 1 packet
5473 if (!writer->WriteVarInt62(0)) {
5474 set_detailed_error("No room for first ack block in ack frame");
5475 return false;
5476 }
5477 return true;
5478 }
5479 // Case 2 or 3
5480 auto itr = frame.packets.rbegin();
5481
5482 QuicPacketNumber ack_block_largest(largest_acked);
5483 QuicPacketNumber ack_block_smallest;
5484 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5485 // If largest_acked + 1 is equal to the Max() of the first Interval
5486 // in the QuicAckFrame then the first Interval is the first ack block of the
5487 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5488 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5489 // the remaining Intervals are encoded in additional ack blocks in the
5490 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5491 // Intervals - 1.
5492 ack_block_smallest = itr->min();
5493 itr++;
5494 ack_block_count--;
5495 } else {
5496 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5497 // the first Interval then it is interpreted as acking a single
5498 // packet at QuicAckFrame.largest_acked, with additional
5499 // Intervals indicating additional ack blocks. The encoding is
5500 // a) The packet's largest_acked is the QuicAckFrame's largest
5501 // acked,
5502 // b) the first ack block size is 0,
5503 // c) The packet's ack_block_count is the number of QuicAckFrame
5504 // Intervals, and
5505 // d) The QuicAckFrame Intervals are encoded in additional ack
5506 // blocks in the packet.
5507 ack_block_smallest = largest_acked;
5508 }
5509
5510 if (!writer->WriteVarInt62(ack_block_count)) {
5511 set_detailed_error("No room for ack block count in ack frame");
5512 return false;
5513 }
5514
5515 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5516 if (!writer->WriteVarInt62(first_ack_block)) {
5517 set_detailed_error("No room for first ack block in ack frame");
5518 return false;
5519 }
5520
5521 // For the remaining QuicAckFrame Intervals, if any
5522 while (ack_block_count != 0) {
5523 uint64_t gap_size = ack_block_smallest - itr->max();
5524 if (!writer->WriteVarInt62(gap_size - 1)) {
5525 set_detailed_error("No room for gap block in ack frame");
5526 return false;
5527 }
5528
5529 uint64_t block_size = itr->max() - itr->min();
5530 if (!writer->WriteVarInt62(block_size - 1)) {
5531 set_detailed_error("No room for nth ack block in ack frame");
5532 return false;
5533 }
5534
5535 ack_block_smallest = itr->min();
5536 itr++;
5537 ack_block_count--;
5538 }
5539 return true;
5540}
5541
5542bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5543 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005544 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005545 return AppendIetfResetStreamFrame(frame, writer);
5546 }
5547 if (!writer->WriteUInt32(frame.stream_id)) {
5548 return false;
5549 }
5550
5551 if (!writer->WriteUInt64(frame.byte_offset)) {
5552 return false;
5553 }
5554
5555 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5556 if (!writer->WriteUInt32(error_code)) {
5557 return false;
5558 }
5559
5560 return true;
5561}
5562
5563bool QuicFramer::AppendConnectionCloseFrame(
5564 const QuicConnectionCloseFrame& frame,
5565 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005566 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005567 return AppendIetfConnectionCloseFrame(frame, writer);
5568 }
fkastenholze9d71a82019-04-09 05:12:13 -07005569 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005570 if (!writer->WriteUInt32(error_code)) {
5571 return false;
5572 }
5573 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5574 return false;
5575 }
5576 return true;
5577}
5578
5579bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5580 QuicDataWriter* writer) {
5581 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5582 if (!writer->WriteUInt32(error_code)) {
5583 return false;
5584 }
5585 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5586 if (!writer->WriteUInt32(stream_id)) {
5587 return false;
5588 }
5589 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5590 return false;
5591 }
5592 return true;
5593}
5594
5595bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5596 QuicDataWriter* writer) {
5597 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5598 if (!writer->WriteUInt32(stream_id)) {
5599 return false;
5600 }
renjietangd088eab2019-11-21 14:54:41 -08005601 if (!writer->WriteUInt64(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005602 return false;
5603 }
5604 return true;
5605}
5606
5607bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5608 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005609 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005610 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5611 return AppendIetfBlockedFrame(frame, writer);
5612 }
5613 return AppendStreamBlockedFrame(frame, writer);
5614 }
5615 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5616 if (!writer->WriteUInt32(stream_id)) {
5617 return false;
5618 }
5619 return true;
5620}
5621
5622bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5623 QuicDataWriter* writer) {
5624 if (frame.num_padding_bytes == 0) {
5625 return false;
5626 }
5627 if (frame.num_padding_bytes < 0) {
5628 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5629 writer->WritePadding();
5630 return true;
5631 }
5632 // Please note, num_padding_bytes includes type byte which has been written.
5633 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5634}
5635
5636bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5637 bool last_frame_in_packet,
5638 QuicDataWriter* writer) {
dschinazicd86dd12019-11-14 10:11:13 -08005639 uint8_t type_byte;
5640 if (VersionHasIetfQuicFrames(version_.transport_version)) {
5641 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH_V99
5642 : IETF_EXTENSION_MESSAGE_V99;
5643 } else {
5644 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5645 : IETF_EXTENSION_MESSAGE;
5646 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005647 if (!writer->WriteUInt8(type_byte)) {
5648 return false;
5649 }
5650 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5651 return false;
5652 }
5653 for (const auto& slice : frame.message_data) {
5654 if (!writer->WriteBytes(slice.data(), slice.length())) {
5655 return false;
5656 }
5657 }
5658 return true;
5659}
5660
5661bool QuicFramer::RaiseError(QuicErrorCode error) {
5662 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5663 << " detail: " << detailed_error_;
5664 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005665 if (visitor_) {
5666 visitor_->OnError(this);
5667 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005668 return false;
5669}
5670
5671bool QuicFramer::IsVersionNegotiation(
5672 const QuicPacketHeader& header,
5673 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005674 if (!packet_has_ietf_packet_header &&
5675 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005676 return header.version_flag;
5677 }
5678 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5679 return false;
5680 }
5681 return header.long_packet_type == VERSION_NEGOTIATION;
5682}
5683
QUICHE teama6ef0a62019-03-07 20:34:33 -05005684bool QuicFramer::AppendIetfConnectionCloseFrame(
5685 const QuicConnectionCloseFrame& frame,
5686 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005687 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5688 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5689 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5690 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5691 return false;
5692 }
5693
fkastenholz88d08f42019-09-06 07:38:04 -07005694 if (!writer->WriteVarInt62(
5695 (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
5696 ? frame.transport_error_code
5697 : frame.application_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005698 set_detailed_error("Can not write connection close frame error code");
5699 return false;
5700 }
fkastenholze9d71a82019-04-09 05:12:13 -07005701
fkastenholz72f509b2019-04-10 09:17:49 -07005702 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5703 // Write the frame-type of the frame causing the error only
5704 // if it's a CONNECTION_CLOSE/Transport.
5705 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5706 set_detailed_error("Writing frame type failed.");
5707 return false;
5708 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005709 }
5710
fkastenholzb4dade72019-08-05 06:54:20 -07005711 // There may be additional error information available in the extracted error
5712 // code. Encode the error information in the reason phrase and serialize the
5713 // result.
5714 std::string final_error_string =
5715 GenerateErrorString(frame.error_details, frame.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005716 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005717 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005718 set_detailed_error("Can not write connection close phrase");
5719 return false;
5720 }
5721 return true;
5722}
5723
QUICHE teama6ef0a62019-03-07 20:34:33 -05005724bool QuicFramer::ProcessIetfConnectionCloseFrame(
5725 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005726 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005727 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005728 frame->close_type = type;
fkastenholzb4dade72019-08-05 06:54:20 -07005729
fkastenholz88d08f42019-09-06 07:38:04 -07005730 uint64_t error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005731 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005732 set_detailed_error("Unable to read connection close error code.");
5733 return false;
5734 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005735
fkastenholzd57d3f92019-07-16 09:05:17 -07005736 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005737 frame->transport_error_code =
5738 static_cast<QuicIetfTransportErrorCodes>(error_code);
fkastenholzd57d3f92019-07-16 09:05:17 -07005739 } else if (frame->close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005740 frame->application_error_code = error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005741 }
fkastenholzb4dade72019-08-05 06:54:20 -07005742
fkastenholz72f509b2019-04-10 09:17:49 -07005743 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5744 // The frame-type of the frame causing the error is present only
5745 // if it's a CONNECTION_CLOSE/Transport.
5746 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5747 set_detailed_error("Unable to read connection close frame type.");
5748 return false;
5749 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005750 }
5751
5752 uint64_t phrase_length;
5753 if (!reader->ReadVarInt62(&phrase_length)) {
5754 set_detailed_error("Unable to read connection close error details.");
5755 return false;
5756 }
fkastenholzb4dade72019-08-05 06:54:20 -07005757
dmcardlecf0bfcf2019-12-13 08:08:21 -08005758 quiche::QuicheStringPiece phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005759 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5760 set_detailed_error("Unable to read connection close error details.");
5761 return false;
5762 }
vasilvvc48c8712019-03-11 13:38:16 -07005763 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005764
fkastenholzb4dade72019-08-05 06:54:20 -07005765 // The frame may have an extracted error code in it. Look for it and
5766 // extract it. If it's not present, MaybeExtract will return
5767 // QUIC_IETF_GQUIC_ERROR_MISSING.
fkastenholz488a4622019-08-26 06:24:46 -07005768 MaybeExtractQuicErrorCode(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005769 return true;
5770}
5771
5772// IETF Quic Path Challenge/Response frames.
5773bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5774 QuicPathChallengeFrame* frame) {
5775 if (!reader->ReadBytes(frame->data_buffer.data(),
5776 frame->data_buffer.size())) {
5777 set_detailed_error("Can not read path challenge data.");
5778 return false;
5779 }
5780 return true;
5781}
5782
5783bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5784 QuicPathResponseFrame* frame) {
5785 if (!reader->ReadBytes(frame->data_buffer.data(),
5786 frame->data_buffer.size())) {
5787 set_detailed_error("Can not read path response data.");
5788 return false;
5789 }
5790 return true;
5791}
5792
5793bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5794 QuicDataWriter* writer) {
5795 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5796 set_detailed_error("Writing Path Challenge data failed.");
5797 return false;
5798 }
5799 return true;
5800}
5801
5802bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5803 QuicDataWriter* writer) {
5804 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5805 set_detailed_error("Writing Path Response data failed.");
5806 return false;
5807 }
5808 return true;
5809}
5810
5811// Add a new ietf-format stream reset frame.
5812// General format is
5813// stream id
5814// application error code
5815// final offset
5816bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5817 QuicDataWriter* writer) {
5818 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5819 set_detailed_error("Writing reset-stream stream id failed.");
5820 return false;
5821 }
fkastenholz07300e52019-07-16 11:51:37 -07005822 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005823 set_detailed_error("Writing reset-stream error code failed.");
5824 return false;
5825 }
5826 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5827 set_detailed_error("Writing reset-stream final-offset failed.");
5828 return false;
5829 }
5830 return true;
5831}
5832
5833bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5834 QuicRstStreamFrame* frame) {
5835 // Get Stream ID from frame. ReadVarIntStreamID returns false
5836 // if either A) there is a read error or B) the resulting value of
5837 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005838 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005839 set_detailed_error("Unable to read rst stream stream id.");
5840 return false;
5841 }
5842
fkastenholz07300e52019-07-16 11:51:37 -07005843 uint64_t error_code;
5844 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005845 set_detailed_error("Unable to read rst stream error code.");
5846 return false;
5847 }
fkastenholz07300e52019-07-16 11:51:37 -07005848 if (error_code > 0xffff) {
5849 frame->ietf_error_code = 0xffff;
5850 QUIC_DLOG(ERROR) << "Reset stream error code (" << error_code
5851 << ") > 0xffff";
5852 } else {
5853 frame->ietf_error_code = static_cast<uint16_t>(error_code);
5854 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005855
5856 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5857 set_detailed_error("Unable to read rst stream sent byte offset.");
5858 return false;
5859 }
5860 return true;
5861}
5862
5863bool QuicFramer::ProcessStopSendingFrame(
5864 QuicDataReader* reader,
5865 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005866 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005867 set_detailed_error("Unable to read stop sending stream id.");
5868 return false;
5869 }
5870
fkastenholz733552e2019-07-16 11:16:58 -07005871 uint64_t error_code;
5872 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005873 set_detailed_error("Unable to read stop sending application error code.");
5874 return false;
5875 }
fkastenholz733552e2019-07-16 11:16:58 -07005876 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5877 if (error_code > 0xffff) {
5878 stop_sending_frame->application_error_code = 0xffff;
5879 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5880 << ") > 0xffff";
5881 } else {
5882 stop_sending_frame->application_error_code =
5883 static_cast<uint16_t>(error_code);
5884 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005885 return true;
5886}
5887
5888bool QuicFramer::AppendStopSendingFrame(
5889 const QuicStopSendingFrame& stop_sending_frame,
5890 QuicDataWriter* writer) {
5891 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5892 set_detailed_error("Can not write stop sending stream id");
5893 return false;
5894 }
fkastenholz733552e2019-07-16 11:16:58 -07005895 if (!writer->WriteVarInt62(
5896 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005897 set_detailed_error("Can not write application error code");
5898 return false;
5899 }
5900 return true;
5901}
5902
5903// Append/process IETF-Format MAX_DATA Frame
5904bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5905 QuicDataWriter* writer) {
renjietangd088eab2019-11-21 14:54:41 -08005906 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005907 set_detailed_error("Can not write MAX_DATA byte-offset");
5908 return false;
5909 }
5910 return true;
5911}
5912
5913bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5914 QuicWindowUpdateFrame* frame) {
5915 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
renjietangd088eab2019-11-21 14:54:41 -08005916 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005917 set_detailed_error("Can not read MAX_DATA byte-offset");
5918 return false;
5919 }
5920 return true;
5921}
5922
5923// Append/process IETF-Format MAX_STREAM_DATA Frame
5924bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5925 QuicDataWriter* writer) {
5926 if (!writer->WriteVarInt62(frame.stream_id)) {
5927 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5928 return false;
5929 }
renjietangd088eab2019-11-21 14:54:41 -08005930 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005931 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5932 return false;
5933 }
5934 return true;
5935}
5936
5937bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5938 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005939 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005940 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5941 return false;
5942 }
renjietangd088eab2019-11-21 14:54:41 -08005943 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005944 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5945 return false;
5946 }
5947 return true;
5948}
5949
fkastenholz3c4eabf2019-04-22 07:49:59 -07005950bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005951 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005952 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005953 set_detailed_error("Can not write MAX_STREAMS stream count");
5954 return false;
5955 }
5956 return true;
5957}
5958
5959bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005960 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005961 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005962 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005963 set_detailed_error("Can not read MAX_STREAMS stream count.");
5964 return false;
5965 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005966 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
5967 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005968}
5969
5970bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
5971 QuicDataWriter* writer) {
5972 if (!writer->WriteVarInt62(frame.offset)) {
5973 set_detailed_error("Can not write blocked offset.");
5974 return false;
5975 }
5976 return true;
5977}
5978
5979bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
5980 QuicBlockedFrame* frame) {
5981 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
5982 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5983 if (!reader->ReadVarInt62(&frame->offset)) {
5984 set_detailed_error("Can not read blocked offset.");
5985 return false;
5986 }
5987 return true;
5988}
5989
5990bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
5991 QuicDataWriter* writer) {
5992 if (!writer->WriteVarInt62(frame.stream_id)) {
5993 set_detailed_error("Can not write stream blocked stream id.");
5994 return false;
5995 }
5996 if (!writer->WriteVarInt62(frame.offset)) {
5997 set_detailed_error("Can not write stream blocked offset.");
5998 return false;
5999 }
6000 return true;
6001}
6002
6003bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
6004 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006005 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006006 set_detailed_error("Can not read stream blocked stream id.");
6007 return false;
6008 }
6009 if (!reader->ReadVarInt62(&frame->offset)) {
6010 set_detailed_error("Can not read stream blocked offset.");
6011 return false;
6012 }
6013 return true;
6014}
6015
fkastenholz3c4eabf2019-04-22 07:49:59 -07006016bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6017 QuicDataWriter* writer) {
6018 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006019 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6020 return false;
6021 }
6022 return true;
6023}
6024
6025bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006026 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006027 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006028 if (!reader->ReadVarIntU32(&frame->stream_count)) {
6029 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006030 return false;
6031 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006032 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
fkastenholz3c4eabf2019-04-22 07:49:59 -07006033 if (frame->stream_count >
6034 QuicUtils::GetMaxStreamCount(
6035 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
6036 ((perspective_ == Perspective::IS_CLIENT)
6037 ? Perspective::IS_SERVER
6038 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006039 // If stream count is such that the resulting stream ID would exceed our
6040 // implementation limit, generate an error.
6041 set_detailed_error(
6042 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6043 return false;
6044 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006045 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006046}
6047
6048bool QuicFramer::AppendNewConnectionIdFrame(
6049 const QuicNewConnectionIdFrame& frame,
6050 QuicDataWriter* writer) {
6051 if (!writer->WriteVarInt62(frame.sequence_number)) {
6052 set_detailed_error("Can not write New Connection ID sequence number");
6053 return false;
6054 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006055 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6056 set_detailed_error("Can not write New Connection ID retire_prior_to");
6057 return false;
6058 }
dschinazicf5b1e22019-07-17 18:35:17 -07006059 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006060 set_detailed_error("Can not write New Connection ID frame connection ID");
6061 return false;
6062 }
6063
6064 if (!writer->WriteBytes(
6065 static_cast<const void*>(&frame.stateless_reset_token),
6066 sizeof(frame.stateless_reset_token))) {
6067 set_detailed_error("Can not write New Connection ID Reset Token");
6068 return false;
6069 }
6070 return true;
6071}
6072
6073bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6074 QuicNewConnectionIdFrame* frame) {
6075 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6076 set_detailed_error(
6077 "Unable to read new connection ID frame sequence number.");
6078 return false;
6079 }
6080
fkastenholz1c19fc22019-07-12 11:06:19 -07006081 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6082 set_detailed_error(
6083 "Unable to read new connection ID frame retire_prior_to.");
6084 return false;
6085 }
6086 if (frame->retire_prior_to > frame->sequence_number) {
6087 set_detailed_error("Retire_prior_to > sequence_number.");
6088 return false;
6089 }
dschinazicf5b1e22019-07-17 18:35:17 -07006090
6091 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6092 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006093 return false;
6094 }
6095
dschinazicf5b1e22019-07-17 18:35:17 -07006096 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6097 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006098 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006099 return false;
6100 }
6101
QUICHE teama6ef0a62019-03-07 20:34:33 -05006102 if (!reader->ReadBytes(&frame->stateless_reset_token,
6103 sizeof(frame->stateless_reset_token))) {
6104 set_detailed_error("Can not read new connection ID frame reset token.");
6105 return false;
6106 }
6107 return true;
6108}
6109
6110bool QuicFramer::AppendRetireConnectionIdFrame(
6111 const QuicRetireConnectionIdFrame& frame,
6112 QuicDataWriter* writer) {
6113 if (!writer->WriteVarInt62(frame.sequence_number)) {
6114 set_detailed_error("Can not write Retire Connection ID sequence number");
6115 return false;
6116 }
6117 return true;
6118}
6119
6120bool QuicFramer::ProcessRetireConnectionIdFrame(
6121 QuicDataReader* reader,
6122 QuicRetireConnectionIdFrame* frame) {
6123 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6124 set_detailed_error(
6125 "Unable to read retire connection ID frame sequence number.");
6126 return false;
6127 }
6128 return true;
6129}
6130
6131uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6132 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006133 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006134 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6135 }
6136 uint8_t type_byte = 0;
6137 // Fin bit.
6138 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6139
6140 // Data Length bit.
6141 type_byte <<= kQuicStreamDataLengthShift;
6142 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6143
6144 // Offset 3 bits.
6145 type_byte <<= kQuicStreamShift;
renjietang488201d2019-12-17 13:40:49 -08006146 const size_t offset_len = GetStreamOffsetSize(frame.offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006147 if (offset_len > 0) {
6148 type_byte |= offset_len - 1;
6149 }
6150
6151 // stream id 2 bits.
6152 type_byte <<= kQuicStreamIdShift;
6153 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6154 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6155
6156 return type_byte;
6157}
6158
6159uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6160 const QuicStreamFrame& frame,
6161 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006162 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006163 uint8_t type_byte = IETF_STREAM;
6164 if (!last_frame_in_packet) {
6165 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6166 }
6167 if (frame.offset != 0) {
6168 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6169 }
6170 if (frame.fin) {
6171 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6172 }
6173 return type_byte;
6174}
6175
6176void QuicFramer::InferPacketHeaderTypeFromVersion() {
6177 // This function should only be called when server connection negotiates the
6178 // version.
bncbe885272020-01-16 11:10:48 -08006179 DCHECK_EQ(perspective_, Perspective::IS_SERVER);
6180 DCHECK(!infer_packet_header_type_from_version_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006181 infer_packet_header_type_from_version_ = true;
6182}
6183
QUICHE team10b22a12019-03-21 15:31:42 -07006184void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6185 if (supports_multiple_packet_number_spaces_) {
6186 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6187 return;
6188 }
6189 if (largest_packet_number_.IsInitialized()) {
6190 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6191 "packet has been received.";
6192 return;
6193 }
6194
6195 supports_multiple_packet_number_spaces_ = true;
6196}
6197
fayangccbab732019-05-13 10:11:25 -07006198// static
dschinazi48ac9192019-07-31 00:07:26 -07006199QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6200 const QuicEncryptedPacket& packet,
6201 uint8_t expected_destination_connection_id_length,
6202 PacketHeaderFormat* format,
fayange3f2f7b2019-09-19 17:01:57 -07006203 QuicLongHeaderType* long_packet_type,
dschinazi48ac9192019-07-31 00:07:26 -07006204 bool* version_present,
6205 bool* has_length_prefix,
6206 QuicVersionLabel* version_label,
6207 ParsedQuicVersion* parsed_version,
6208 QuicConnectionId* destination_connection_id,
6209 QuicConnectionId* source_connection_id,
6210 bool* retry_token_present,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006211 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006212 std::string* detailed_error) {
6213 QuicDataReader reader(packet.data(), packet.length());
6214 if (reader.IsDoneReading()) {
6215 *detailed_error = "Unable to read first byte.";
6216 return QUIC_INVALID_PACKET_HEADER;
6217 }
6218 const uint8_t first_byte = reader.PeekByte();
6219 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6220 uint8_t unused_first_byte;
6221 QuicVariableLengthIntegerLength retry_token_length_length;
fayange3f2f7b2019-09-19 17:01:57 -07006222 QuicErrorCode error_code = ParsePublicHeader(
dschinazi48ac9192019-07-31 00:07:26 -07006223 &reader, expected_destination_connection_id_length, ietf_format,
6224 &unused_first_byte, format, version_present, has_length_prefix,
6225 version_label, parsed_version, destination_connection_id,
fayange3f2f7b2019-09-19 17:01:57 -07006226 source_connection_id, long_packet_type, &retry_token_length_length,
dschinazi48ac9192019-07-31 00:07:26 -07006227 retry_token, detailed_error);
6228 *retry_token_present =
6229 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6230 return error_code;
6231}
6232
6233// static
6234QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6235 QuicDataReader* reader,
6236 uint8_t* first_byte,
6237 PacketHeaderFormat* format,
6238 bool* version_present,
6239 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006240 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006241 QuicConnectionId* destination_connection_id,
6242 std::string* detailed_error) {
6243 *format = GOOGLE_QUIC_PACKET;
6244 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6245 uint8_t destination_connection_id_length = 0;
6246 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6247 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6248 }
6249 if (!reader->ReadConnectionId(destination_connection_id,
6250 destination_connection_id_length)) {
6251 *detailed_error = "Unable to read ConnectionId.";
6252 return QUIC_INVALID_PACKET_HEADER;
6253 }
dschinazi243eabc2019-08-05 16:15:29 -07006254 if (*version_present) {
6255 if (!ProcessVersionLabel(reader, version_label)) {
6256 *detailed_error = "Unable to read protocol version.";
6257 return QUIC_INVALID_PACKET_HEADER;
6258 }
6259 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006260 }
6261 return QUIC_NO_ERROR;
6262}
6263
6264namespace {
6265
dschinazi81eb4e02019-09-27 17:12:17 -07006266const QuicVersionLabel kProxVersionLabel = 0x50524F58; // "PROX"
6267
dschinazi48ac9192019-07-31 00:07:26 -07006268inline bool PacketHasLengthPrefixedConnectionIds(
6269 const QuicDataReader& reader,
6270 ParsedQuicVersion parsed_version,
6271 QuicVersionLabel version_label,
6272 uint8_t first_byte) {
6273 if (parsed_version.transport_version != QUIC_VERSION_UNSUPPORTED) {
6274 return parsed_version.HasLengthPrefixedConnectionIds();
6275 }
6276
6277 // Received unsupported version, check known old unsupported versions.
6278 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6279 return false;
6280 }
6281
6282 // Received unknown version, check connection ID length byte.
6283 if (reader.IsDoneReading()) {
6284 // This check is required to safely peek the connection ID length byte.
6285 return true;
6286 }
6287 const uint8_t connection_id_length_byte = reader.PeekByte();
6288
6289 // Check for packets produced by older versions of
6290 // QuicFramer::WriteClientVersionNegotiationProbePacket
6291 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6292 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6293 return false;
6294 }
6295
6296 // Check for munged packets with version tag PROX.
6297 if ((connection_id_length_byte & 0x0f) == 0 &&
dschinazi81eb4e02019-09-27 17:12:17 -07006298 connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) {
dschinazi48ac9192019-07-31 00:07:26 -07006299 return false;
6300 }
6301
6302 return true;
6303}
6304
6305inline bool ParseLongHeaderConnectionIds(
6306 QuicDataReader* reader,
6307 bool has_length_prefix,
dschinazi81eb4e02019-09-27 17:12:17 -07006308 QuicVersionLabel version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006309 QuicConnectionId* destination_connection_id,
6310 QuicConnectionId* source_connection_id,
6311 std::string* detailed_error) {
6312 if (has_length_prefix) {
6313 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6314 *detailed_error = "Unable to read destination connection ID.";
6315 return false;
6316 }
6317 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
dschinazi68fad8e2019-11-04 10:07:21 -08006318 if (version_label == kProxVersionLabel) {
dschinazi81eb4e02019-09-27 17:12:17 -07006319 // The "PROX" version does not follow the length-prefixed invariants,
6320 // and can therefore attempt to read a payload byte and interpret it
6321 // as the source connection ID length, which could fail to parse.
6322 // In that scenario we keep the source connection ID empty but mark
6323 // parsing as successful.
6324 return true;
6325 }
dschinazi48ac9192019-07-31 00:07:26 -07006326 *detailed_error = "Unable to read source connection ID.";
6327 return false;
6328 }
6329 } else {
6330 // Parse connection ID lengths.
6331 uint8_t connection_id_lengths_byte;
6332 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6333 *detailed_error = "Unable to read connection ID lengths.";
6334 return false;
6335 }
6336 uint8_t destination_connection_id_length =
6337 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6338 if (destination_connection_id_length != 0) {
6339 destination_connection_id_length += kConnectionIdLengthAdjustment;
6340 }
6341 uint8_t source_connection_id_length =
6342 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6343 if (source_connection_id_length != 0) {
6344 source_connection_id_length += kConnectionIdLengthAdjustment;
6345 }
6346
6347 // Read destination connection ID.
6348 if (!reader->ReadConnectionId(destination_connection_id,
6349 destination_connection_id_length)) {
6350 *detailed_error = "Unable to read destination connection ID.";
6351 return false;
6352 }
6353
6354 // Read source connection ID.
6355 if (!reader->ReadConnectionId(source_connection_id,
6356 source_connection_id_length)) {
6357 *detailed_error = "Unable to read source connection ID.";
6358 return false;
6359 }
6360 }
6361 return true;
6362}
6363
6364} // namespace
6365
6366// static
6367QuicErrorCode QuicFramer::ParsePublicHeader(
6368 QuicDataReader* reader,
6369 uint8_t expected_destination_connection_id_length,
6370 bool ietf_format,
6371 uint8_t* first_byte,
6372 PacketHeaderFormat* format,
6373 bool* version_present,
6374 bool* has_length_prefix,
6375 QuicVersionLabel* version_label,
6376 ParsedQuicVersion* parsed_version,
6377 QuicConnectionId* destination_connection_id,
6378 QuicConnectionId* source_connection_id,
6379 QuicLongHeaderType* long_packet_type,
6380 QuicVariableLengthIntegerLength* retry_token_length_length,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006381 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006382 std::string* detailed_error) {
6383 *version_present = false;
6384 *has_length_prefix = false;
6385 *version_label = 0;
6386 *parsed_version = UnsupportedQuicVersion();
6387 *source_connection_id = EmptyQuicConnectionId();
6388 *long_packet_type = INVALID_PACKET_TYPE;
6389 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006390 *retry_token = quiche::QuicheStringPiece();
dschinazi48ac9192019-07-31 00:07:26 -07006391 *detailed_error = "";
6392
6393 if (!reader->ReadUInt8(first_byte)) {
6394 *detailed_error = "Unable to read first byte.";
6395 return QUIC_INVALID_PACKET_HEADER;
6396 }
6397
6398 if (!ietf_format) {
6399 return ParsePublicHeaderGoogleQuic(
6400 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006401 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006402 }
6403
6404 *format = GetIetfPacketHeaderFormat(*first_byte);
6405
6406 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6407 // Read destination connection ID using
6408 // expected_destination_connection_id_length to determine its length.
6409 if (!reader->ReadConnectionId(destination_connection_id,
6410 expected_destination_connection_id_length)) {
6411 *detailed_error = "Unable to read destination connection ID.";
6412 return QUIC_INVALID_PACKET_HEADER;
6413 }
6414 return QUIC_NO_ERROR;
6415 }
6416
6417 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6418 *version_present = true;
6419 if (!ProcessVersionLabel(reader, version_label)) {
6420 *detailed_error = "Unable to read protocol version.";
6421 return QUIC_INVALID_PACKET_HEADER;
6422 }
6423
6424 if (*version_label == 0) {
6425 *long_packet_type = VERSION_NEGOTIATION;
6426 }
6427
6428 // Parse version.
6429 *parsed_version = ParseQuicVersionLabel(*version_label);
6430
6431 // Figure out which IETF QUIC invariants this packet follows.
6432 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6433 *reader, *parsed_version, *version_label, *first_byte);
6434
6435 // Parse connection IDs.
dschinazi81eb4e02019-09-27 17:12:17 -07006436 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix, *version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006437 destination_connection_id,
6438 source_connection_id, detailed_error)) {
6439 return QUIC_INVALID_PACKET_HEADER;
6440 }
6441
6442 if (parsed_version->transport_version == QUIC_VERSION_UNSUPPORTED) {
6443 // Skip parsing of long packet type and retry token for unknown versions.
6444 return QUIC_NO_ERROR;
6445 }
6446
6447 // Parse long packet type.
fayang36825da2019-08-21 14:01:27 -07006448 if (!GetLongHeaderType(*first_byte, long_packet_type)) {
dschinazi48ac9192019-07-31 00:07:26 -07006449 *detailed_error = "Unable to parse long packet type.";
6450 return QUIC_INVALID_PACKET_HEADER;
6451 }
6452
6453 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6454 // Retry token is only present on initial packets for some versions.
6455 return QUIC_NO_ERROR;
6456 }
6457
6458 *retry_token_length_length = reader->PeekVarInt62Length();
6459 uint64_t retry_token_length;
6460 if (!reader->ReadVarInt62(&retry_token_length)) {
6461 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6462 *detailed_error = "Unable to read retry token length.";
6463 return QUIC_INVALID_PACKET_HEADER;
6464 }
6465
6466 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6467 *detailed_error = "Unable to read retry token.";
6468 return QUIC_INVALID_PACKET_HEADER;
6469 }
6470
6471 return QUIC_NO_ERROR;
6472}
6473
6474// static
dschinazide0f6dc2019-05-15 16:10:11 -07006475bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6476 char* packet_bytes,
6477 QuicByteCount packet_length,
6478 const char* destination_connection_id_bytes,
6479 uint8_t destination_connection_id_length) {
6480 if (packet_bytes == nullptr) {
6481 QUIC_BUG << "Invalid packet_bytes";
6482 return false;
6483 }
6484 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6485 packet_length > 65535) {
6486 QUIC_BUG << "Invalid packet_length";
6487 return false;
6488 }
dschinazib012d212019-08-01 18:07:26 -07006489 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006490 destination_connection_id_length <
6491 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006492 QUIC_BUG << "Invalid connection_id_length";
6493 return false;
6494 }
dschinazi48ac9192019-07-31 00:07:26 -07006495 const bool use_length_prefix =
6496 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6497 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006498 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006499 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006500 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6501 0xc0,
6502 // Version, part of the IETF space reserved for negotiation.
6503 // This intentionally differs from QuicVersionReservedForNegotiation()
6504 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006505 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006506 };
6507 // clang-format on
6508 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6509 QuicDataWriter writer(packet_length, packet_bytes);
6510 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6511 QUIC_BUG << "Failed to write packet start";
6512 return false;
6513 }
6514
6515 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6516 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006517 if (!AppendIetfConnectionIds(
6518 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6519 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006520 QUIC_BUG << "Failed to write connection IDs";
6521 return false;
6522 }
6523 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6524 // not parse with any known version. The zeroes make sure that packet numbers,
6525 // retry token lengths and payload lengths are parsed as zero, and if the
6526 // zeroes are treated as padding frames, 0xff is known to not parse as a
6527 // valid frame type.
6528 if (!writer.WriteUInt64(0) ||
6529 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6530 QUIC_BUG << "Failed to write 18 bytes";
6531 return false;
6532 }
6533 // Make sure the polite greeting below is padded to a 16-byte boundary to
6534 // make it easier to read in tcpdump.
6535 while (writer.length() % 16 != 0) {
6536 if (!writer.WriteUInt8(0)) {
6537 QUIC_BUG << "Failed to write padding byte";
6538 return false;
6539 }
6540 }
6541 // Add a polite greeting in case a human sees this in tcpdump.
6542 static const char polite_greeting[] =
6543 "This packet only exists to trigger IETF QUIC version negotiation. "
6544 "Please respond with a Version Negotiation packet indicating what "
6545 "versions you support. Thank you and have a nice day.";
6546 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6547 QUIC_BUG << "Failed to write polite greeting";
6548 return false;
6549 }
6550 // Fill the rest of the packet with zeroes.
6551 writer.WritePadding();
6552 DCHECK_EQ(0u, writer.remaining());
6553 return true;
6554}
6555
6556// static
6557bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6558 const char* packet_bytes,
6559 QuicByteCount packet_length,
6560 char* source_connection_id_bytes,
6561 uint8_t* source_connection_id_length_out,
6562 std::string* detailed_error) {
6563 if (detailed_error == nullptr) {
6564 QUIC_BUG << "Invalid error_details";
6565 return false;
6566 }
6567 *detailed_error = "";
6568 if (packet_bytes == nullptr) {
6569 *detailed_error = "Invalid packet_bytes";
6570 return false;
6571 }
6572 if (packet_length < 6) {
6573 *detailed_error = "Invalid packet_length";
6574 return false;
6575 }
6576 if (source_connection_id_bytes == nullptr) {
6577 *detailed_error = "Invalid source_connection_id_bytes";
6578 return false;
6579 }
6580 if (source_connection_id_length_out == nullptr) {
6581 *detailed_error = "Invalid source_connection_id_length_out";
6582 return false;
6583 }
6584 QuicDataReader reader(packet_bytes, packet_length);
6585 uint8_t type_byte = 0;
6586 if (!reader.ReadUInt8(&type_byte)) {
6587 *detailed_error = "Failed to read type byte";
6588 return false;
6589 }
6590 if ((type_byte & 0x80) == 0) {
6591 *detailed_error = "Packet does not have long header";
6592 return false;
6593 }
6594 uint32_t version = 0;
6595 if (!reader.ReadUInt32(&version)) {
6596 *detailed_error = "Failed to read version";
6597 return false;
6598 }
6599 if (version != 0) {
6600 *detailed_error = "Packet is not a version negotiation packet";
6601 return false;
6602 }
dschinazi48ac9192019-07-31 00:07:26 -07006603 const bool use_length_prefix =
6604 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006605 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006606 if (use_length_prefix) {
6607 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6608 *detailed_error = "Failed to read destination connection ID";
6609 return false;
6610 }
6611 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6612 *detailed_error = "Failed to read source connection ID";
6613 return false;
6614 }
6615 } else {
6616 uint8_t expected_server_connection_id_length = 0,
6617 destination_connection_id_length = 0,
6618 source_connection_id_length = 0;
6619 if (!ProcessAndValidateIetfConnectionIdLength(
6620 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6621 /*should_update_expected_server_connection_id_length=*/true,
6622 &expected_server_connection_id_length,
6623 &destination_connection_id_length, &source_connection_id_length,
6624 detailed_error)) {
6625 return false;
6626 }
6627 if (!reader.ReadConnectionId(&destination_connection_id,
6628 destination_connection_id_length)) {
6629 *detailed_error = "Failed to read destination connection ID";
6630 return false;
6631 }
6632 if (!reader.ReadConnectionId(&source_connection_id,
6633 source_connection_id_length)) {
6634 *detailed_error = "Failed to read source connection ID";
6635 return false;
6636 }
dschinazide0f6dc2019-05-15 16:10:11 -07006637 }
dschinazi48ac9192019-07-31 00:07:26 -07006638
6639 if (destination_connection_id.length() != 0) {
6640 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006641 return false;
6642 }
6643
6644 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006645 source_connection_id.length());
6646 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006647
6648 return true;
6649}
6650
fkastenholzb4dade72019-08-05 06:54:20 -07006651// Look for and parse the error code from the "<quic_error_code>:" text that
6652// may be present at the start of the CONNECTION_CLOSE error details string.
6653// This text, inserted by the peer if it's using Google's QUIC implementation,
6654// contains additional error information that narrows down the exact error. If
6655// the string is not found, or is not properly formed, it returns
6656// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
fkastenholz488a4622019-08-26 06:24:46 -07006657void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08006658 std::vector<quiche::QuicheStringPiece> ed =
6659 quiche::QuicheTextUtils::Split(frame->error_details, ':');
fkastenholzb4dade72019-08-05 06:54:20 -07006660 uint64_t extracted_error_code;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006661 if (ed.size() < 2 || !quiche::QuicheTextUtils::IsAllDigits(ed[0]) ||
6662 !quiche::QuicheTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
dschinazidce90b02019-10-14 18:19:54 -07006663 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
6664 frame->transport_error_code == NO_IETF_QUIC_ERROR) {
6665 frame->extracted_error_code = QUIC_NO_ERROR;
6666 } else {
6667 frame->extracted_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
6668 }
fkastenholz488a4622019-08-26 06:24:46 -07006669 return;
fkastenholzb4dade72019-08-05 06:54:20 -07006670 }
fkastenholz488a4622019-08-26 06:24:46 -07006671 // Return the error code (numeric) and the error details string without the
6672 // error code prefix. Note that Split returns everything up to, but not
6673 // including, the split character, so the length of ed[0] is just the number
6674 // of digits in the error number. In removing the prefix, 1 is added to the
6675 // length to account for the :
dmcardlecf0bfcf2019-12-13 08:08:21 -08006676 quiche::QuicheStringPiece x = quiche::QuicheStringPiece(frame->error_details);
fkastenholz488a4622019-08-26 06:24:46 -07006677 x.remove_prefix(ed[0].length() + 1);
6678 frame->error_details = std::string(x);
6679 frame->extracted_error_code =
6680 static_cast<QuicErrorCode>(extracted_error_code);
fkastenholzb4dade72019-08-05 06:54:20 -07006681}
6682
QUICHE teama6ef0a62019-03-07 20:34:33 -05006683#undef ENDPOINT // undef for jumbo builds
6684} // namespace quic