blob: 1170595e60e4fb316b9b04e309b01c511408823b [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,
323 QuicTransportVersion version) {
QUICHE team577718a2019-03-20 09:00:59 -0700324 return full_packet_number > 0 || version == QUIC_VERSION_99;
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];
dschinazi97da52b2020-01-13 15:44:43 -0800426 DCHECK(version_.IsKnown() ||
dschinazi577b5482020-01-13 15:40:43 -0800427 !GetQuicRestartFlag(quic_fix_handling_of_bad_prox_packet))
428 << ParsedQuicVersionVectorToString(supported_versions_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500429}
430
431QuicFramer::~QuicFramer() {}
432
433// static
434size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
435 QuicStreamId stream_id,
436 QuicStreamOffset offset,
437 bool last_frame_in_packet,
fkastenholzabfd9ec2019-10-31 07:59:12 -0700438 size_t data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700439 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500440 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
441 (last_frame_in_packet
442 ? 0
443 : QuicDataWriter::GetVarInt62Len(data_length)) +
444 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
445 }
446 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
renjietang488201d2019-12-17 13:40:49 -0800447 GetStreamOffsetSize(offset) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500448 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
449}
450
451// static
452size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
453 QuicPacketLength data_length) {
454 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
455 QuicDataWriter::GetVarInt62Len(data_length);
456}
457
458// static
459size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
460 bool last_frame_in_packet,
461 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700462 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500463 << "Try to serialize MESSAGE frame in " << version;
464 return kQuicFrameTypeSize +
465 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
466 length;
467}
468
469// static
470size_t QuicFramer::GetMinAckFrameSize(
471 QuicTransportVersion version,
472 QuicPacketNumberLength largest_observed_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700473 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500474 // The minimal ack frame consists of the following four fields: Largest
475 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
476 // size of each is 1 byte.
477 return kQuicFrameTypeSize + 4;
478 }
479 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
480 kQuicDeltaTimeLargestObservedSize;
481 return min_size + kQuicNumTimestampsSize;
482}
483
484// static
485size_t QuicFramer::GetStopWaitingFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500486 QuicPacketNumberLength packet_number_length) {
487 size_t min_size = kQuicFrameTypeSize + packet_number_length;
488 return min_size;
489}
490
491// static
492size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
493 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700494 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500495 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
496 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700497 kQuicFrameTypeSize +
498 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500499 }
500 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
501 kQuicErrorCodeSize;
502}
503
504// static
fkastenholza037b8b2019-05-07 06:00:05 -0700505size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500506 QuicTransportVersion version,
507 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700508 if (!VersionHasIetfQuicFrames(version)) {
509 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700510 return kQuicFrameTypeSize + kQuicErrorCodeSize +
511 kQuicErrorDetailsLengthSize +
512 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500513 }
fkastenholzb4dade72019-08-05 06:54:20 -0700514
515 // Prepend the extra error information to the string and get the result's
516 // length.
517 const size_t truncated_error_string_size = TruncatedErrorStringSize(
518 GenerateErrorString(frame.error_details, frame.extracted_error_code));
519
fkastenholza037b8b2019-05-07 06:00:05 -0700520 const size_t frame_size =
521 truncated_error_string_size +
522 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholz88d08f42019-09-06 07:38:04 -0700523 kQuicFrameTypeSize +
524 QuicDataWriter::GetVarInt62Len(
525 (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
526 ? frame.transport_error_code
527 : frame.application_error_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700528 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
529 return frame_size;
530 }
fkastenholzb4dade72019-08-05 06:54:20 -0700531 // The Transport close frame has the transport_close_frame_type, so include
532 // its length.
fkastenholza037b8b2019-05-07 06:00:05 -0700533 return frame_size +
534 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500535}
536
537// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500538size_t QuicFramer::GetMinGoAwayFrameSize() {
539 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
540 kQuicMaxStreamIdSize;
541}
542
543// static
544size_t QuicFramer::GetWindowUpdateFrameSize(
545 QuicTransportVersion version,
546 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700547 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500548 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
549 }
550 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
551 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
renjietangd088eab2019-11-21 14:54:41 -0800552 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500553 }
554 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
555 // fields.
renjietangd088eab2019-11-21 14:54:41 -0800556 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500557 QuicDataWriter::GetVarInt62Len(frame.stream_id);
558}
559
560// static
561size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700562 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700563 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500564 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700565 << ", which does not support IETF Frames, and tried to serialize "
566 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500567 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700568 return kQuicFrameTypeSize +
569 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500570}
571
572// static
573size_t QuicFramer::GetStreamsBlockedFrameSize(
574 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700575 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700576 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500577 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700578 << ", which does not support IETF frames, and tried to serialize "
579 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500580 }
581
fkastenholz3c4eabf2019-04-22 07:49:59 -0700582 return kQuicFrameTypeSize +
583 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500584}
585
586// static
587size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
588 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700589 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500590 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
591 }
592 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
593 // return size of IETF QUIC Blocked frame
594 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
595 }
596 // return size of IETF QUIC Stream Blocked frame.
597 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
598 QuicDataWriter::GetVarInt62Len(frame.stream_id);
599}
600
601// static
602size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
603 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700604 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500605}
606
607// static
608size_t QuicFramer::GetPathChallengeFrameSize(
609 const QuicPathChallengeFrame& frame) {
610 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
611}
612
613// static
614size_t QuicFramer::GetPathResponseFrameSize(
615 const QuicPathResponseFrame& frame) {
616 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
617}
618
619// static
620size_t QuicFramer::GetRetransmittableControlFrameSize(
621 QuicTransportVersion version,
622 const QuicFrame& frame) {
623 switch (frame.type) {
624 case PING_FRAME:
625 // Ping has no payload.
626 return kQuicFrameTypeSize;
627 case RST_STREAM_FRAME:
628 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
629 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700630 return GetConnectionCloseFrameSize(version,
631 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500632 case GOAWAY_FRAME:
633 return GetMinGoAwayFrameSize() +
634 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
635 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700636 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500637 // GetWindowUpdateFrameSize figures this out and returns the correct
638 // length.
639 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
640 case BLOCKED_FRAME:
641 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500642 case NEW_CONNECTION_ID_FRAME:
643 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
644 case RETIRE_CONNECTION_ID_FRAME:
645 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
646 case NEW_TOKEN_FRAME:
647 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700648 case MAX_STREAMS_FRAME:
649 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
650 case STREAMS_BLOCKED_FRAME:
651 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500652 case PATH_RESPONSE_FRAME:
653 return GetPathResponseFrameSize(*frame.path_response_frame);
654 case PATH_CHALLENGE_FRAME:
655 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
656 case STOP_SENDING_FRAME:
657 return GetStopSendingFrameSize(*frame.stop_sending_frame);
fayang01062942020-01-22 07:23:23 -0800658 case HANDSHAKE_DONE_FRAME:
659 // HANDSHAKE_DONE has no payload.
660 return kQuicFrameTypeSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500661
662 case STREAM_FRAME:
663 case ACK_FRAME:
664 case STOP_WAITING_FRAME:
665 case MTU_DISCOVERY_FRAME:
666 case PADDING_FRAME:
667 case MESSAGE_FRAME:
668 case CRYPTO_FRAME:
669 case NUM_FRAME_TYPES:
670 DCHECK(false);
671 return 0;
672 }
673
674 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
675 DCHECK(false);
676 return 0;
677}
678
679// static
680size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
681 // Sizes are 1 through 4 bytes.
682 for (int i = 1; i <= 4; ++i) {
683 stream_id >>= 8;
684 if (stream_id == 0) {
685 return i;
686 }
687 }
688 QUIC_BUG << "Failed to determine StreamIDSize.";
689 return 4;
690}
691
692// static
renjietang488201d2019-12-17 13:40:49 -0800693size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500694 // 0 is a special case.
695 if (offset == 0) {
696 return 0;
697 }
698 // 2 through 8 are the remaining sizes.
699 offset >>= 8;
700 for (int i = 2; i <= 8; ++i) {
701 offset >>= 8;
702 if (offset == 0) {
703 return i;
704 }
705 }
706 QUIC_BUG << "Failed to determine StreamOffsetSize.";
707 return 8;
708}
709
710// static
711size_t QuicFramer::GetNewConnectionIdFrameSize(
712 const QuicNewConnectionIdFrame& frame) {
713 return kQuicFrameTypeSize +
714 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700715 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500716 kConnectionIdLengthSize + frame.connection_id.length() +
717 sizeof(frame.stateless_reset_token);
718}
719
720// static
721size_t QuicFramer::GetRetireConnectionIdFrameSize(
722 const QuicRetireConnectionIdFrame& frame) {
723 return kQuicFrameTypeSize +
724 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
725}
726
727// static
728size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
729 return kQuicFrameTypeSize +
730 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
731 frame.token.length();
732}
733
734// TODO(nharper): Change this method to take a ParsedQuicVersion.
735bool QuicFramer::IsSupportedTransportVersion(
736 const QuicTransportVersion version) const {
737 for (ParsedQuicVersion supported_version : supported_versions_) {
738 if (version == supported_version.transport_version) {
739 return true;
740 }
741 }
742 return false;
743}
744
745bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
746 for (const ParsedQuicVersion& supported_version : supported_versions_) {
747 if (version == supported_version) {
748 return true;
749 }
750 }
751 return false;
752}
753
754size_t QuicFramer::GetSerializedFrameLength(
755 const QuicFrame& frame,
756 size_t free_bytes,
757 bool first_frame,
758 bool last_frame,
759 QuicPacketNumberLength packet_number_length) {
760 // Prevent a rare crash reported in b/19458523.
761 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
762 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
763 << free_bytes << " first_frame:" << first_frame
764 << " last_frame:" << last_frame
765 << " seq num length:" << packet_number_length;
766 set_error(QUIC_INTERNAL_ERROR);
767 visitor_->OnError(this);
768 return 0;
769 }
770 if (frame.type == PADDING_FRAME) {
771 if (frame.padding_frame.num_padding_bytes == -1) {
772 // Full padding to the end of the packet.
773 return free_bytes;
774 } else {
775 // Lite padding.
776 return free_bytes <
777 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
778 ? free_bytes
779 : frame.padding_frame.num_padding_bytes;
780 }
781 }
782
783 size_t frame_len =
784 ComputeFrameLength(frame, last_frame, packet_number_length);
785 if (frame_len <= free_bytes) {
786 // Frame fits within packet. Note that acks may be truncated.
787 return frame_len;
788 }
789 // Only truncate the first frame in a packet, so if subsequent ones go
790 // over, stop including more frames.
791 if (!first_frame) {
792 return 0;
793 }
794 bool can_truncate =
795 frame.type == ACK_FRAME &&
796 free_bytes >= GetMinAckFrameSize(version_.transport_version,
797 PACKET_6BYTE_PACKET_NUMBER);
798 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700799 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500800 // Note that we may not use every byte of the writer in this case.
801 QUIC_DLOG(INFO) << ENDPOINT
802 << "Truncating large frame, free bytes: " << free_bytes;
803 return free_bytes;
804 }
805 return 0;
806}
807
808QuicFramer::AckFrameInfo::AckFrameInfo()
809 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
810
811QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
812
813QuicFramer::AckFrameInfo::~AckFrameInfo() {}
814
815bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
816 QuicDataWriter* writer,
817 size_t length_field_offset,
818 EncryptionLevel level) {
819 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
820 !header.version_flag || length_field_offset == 0) {
821 return true;
822 }
823 if (writer->length() < length_field_offset ||
824 writer->length() - length_field_offset <
825 kQuicDefaultLongHeaderLengthLength) {
826 set_detailed_error("Invalid length_field_offset.");
827 QUIC_BUG << "Invalid length_field_offset.";
828 return false;
829 }
830 size_t length_to_write = writer->length() - length_field_offset -
831 kQuicDefaultLongHeaderLengthLength;
832 // Add length of auth tag.
833 length_to_write = GetCiphertextSize(level, length_to_write);
834
835 QuicDataWriter length_writer(writer->length() - length_field_offset,
836 writer->data() + length_field_offset);
837 if (!length_writer.WriteVarInt62(length_to_write,
838 kQuicDefaultLongHeaderLengthLength)) {
839 set_detailed_error("Failed to overwrite long header length.");
840 QUIC_BUG << "Failed to overwrite long header length.";
841 return false;
842 }
843 return true;
844}
845
846size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
847 const QuicFrames& frames,
848 char* buffer,
849 size_t packet_length,
850 EncryptionLevel level) {
dschinaziecad9642019-10-01 10:44:17 -0700851 QUIC_BUG_IF(header.version_flag &&
852 VersionHasIetfInvariantHeader(transport_version()) &&
853 header.long_packet_type == RETRY && !frames.empty())
854 << "IETF RETRY packets cannot contain frames " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500855 QuicDataWriter writer(packet_length, buffer);
856 size_t length_field_offset = 0;
857 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
858 QUIC_BUG << "AppendPacketHeader failed";
859 return 0;
860 }
861
fkastenholz305e1732019-06-18 05:01:22 -0700862 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500863 if (AppendIetfFrames(frames, &writer) == 0) {
864 return 0;
865 }
866 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
867 level)) {
868 return 0;
869 }
870 return writer.length();
871 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500872
873 size_t i = 0;
874 for (const QuicFrame& frame : frames) {
875 // Determine if we should write stream frame length in header.
876 const bool last_frame_in_packet = i == frames.size() - 1;
877 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
878 QUIC_BUG << "AppendTypeByte failed";
879 return 0;
880 }
881
882 switch (frame.type) {
883 case PADDING_FRAME:
884 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
885 QUIC_BUG << "AppendPaddingFrame of "
886 << frame.padding_frame.num_padding_bytes << " failed";
887 return 0;
888 }
889 break;
890 case STREAM_FRAME:
891 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
892 &writer)) {
893 QUIC_BUG << "AppendStreamFrame failed";
894 return 0;
895 }
896 break;
897 case ACK_FRAME:
898 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
899 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
900 return 0;
901 }
902 break;
903 case STOP_WAITING_FRAME:
904 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
905 &writer)) {
906 QUIC_BUG << "AppendStopWaitingFrame failed";
907 return 0;
908 }
909 break;
910 case MTU_DISCOVERY_FRAME:
911 // MTU discovery frames are serialized as ping frames.
912 QUIC_FALLTHROUGH_INTENDED;
913 case PING_FRAME:
914 // Ping has no payload.
915 break;
916 case RST_STREAM_FRAME:
917 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
918 QUIC_BUG << "AppendRstStreamFrame failed";
919 return 0;
920 }
921 break;
922 case CONNECTION_CLOSE_FRAME:
923 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
924 &writer)) {
925 QUIC_BUG << "AppendConnectionCloseFrame failed";
926 return 0;
927 }
928 break;
929 case GOAWAY_FRAME:
930 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
931 QUIC_BUG << "AppendGoAwayFrame failed";
932 return 0;
933 }
934 break;
935 case WINDOW_UPDATE_FRAME:
936 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
937 QUIC_BUG << "AppendWindowUpdateFrame failed";
938 return 0;
939 }
940 break;
941 case BLOCKED_FRAME:
942 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
943 QUIC_BUG << "AppendBlockedFrame failed";
944 return 0;
945 }
946 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500947 case NEW_CONNECTION_ID_FRAME:
948 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700949 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500950 return RaiseError(QUIC_INTERNAL_ERROR);
951 case RETIRE_CONNECTION_ID_FRAME:
952 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700953 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
954 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500955 return RaiseError(QUIC_INTERNAL_ERROR);
956 case NEW_TOKEN_FRAME:
957 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700958 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500959 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700960 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500961 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700962 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500963 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700964 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500965 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700966 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500967 return RaiseError(QUIC_INTERNAL_ERROR);
968 case PATH_RESPONSE_FRAME:
969 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700970 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500971 return RaiseError(QUIC_INTERNAL_ERROR);
972 case PATH_CHALLENGE_FRAME:
973 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700974 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500975 return RaiseError(QUIC_INTERNAL_ERROR);
976 case STOP_SENDING_FRAME:
977 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700978 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500979 return RaiseError(QUIC_INTERNAL_ERROR);
980 case MESSAGE_FRAME:
981 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
982 last_frame_in_packet, &writer)) {
983 QUIC_BUG << "AppendMessageFrame failed";
984 return 0;
985 }
986 break;
987 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -0700988 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500989 set_detailed_error(
990 "Attempt to append CRYPTO frame in version prior to 47.");
991 return RaiseError(QUIC_INTERNAL_ERROR);
992 }
993 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
994 QUIC_BUG << "AppendCryptoFrame failed";
995 return 0;
996 }
997 break;
998 default:
999 RaiseError(QUIC_INVALID_FRAME_DATA);
1000 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1001 return 0;
1002 }
1003 ++i;
1004 }
1005
dschinazid1428492019-09-17 23:59:30 -07001006 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) {
1007 return 0;
1008 }
1009
QUICHE teama6ef0a62019-03-07 20:34:33 -05001010 return writer.length();
1011}
1012
1013size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1014 QuicDataWriter* writer) {
1015 size_t i = 0;
1016 for (const QuicFrame& frame : frames) {
1017 // Determine if we should write stream frame length in header.
1018 const bool last_frame_in_packet = i == frames.size() - 1;
1019 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1020 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1021 return 0;
1022 }
1023
1024 switch (frame.type) {
1025 case PADDING_FRAME:
1026 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1027 QUIC_BUG << "AppendPaddingFrame of "
1028 << frame.padding_frame.num_padding_bytes
1029 << " failed: " << detailed_error();
1030 return 0;
1031 }
1032 break;
1033 case STREAM_FRAME:
1034 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1035 writer)) {
1036 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1037 return 0;
1038 }
1039 break;
1040 case ACK_FRAME:
1041 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001042 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1043 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001044 return 0;
1045 }
1046 break;
1047 case STOP_WAITING_FRAME:
1048 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001049 "Attempt to append STOP WAITING frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001050 RaiseError(QUIC_INTERNAL_ERROR);
1051 QUIC_BUG << detailed_error();
1052 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001053 case MTU_DISCOVERY_FRAME:
1054 // MTU discovery frames are serialized as ping frames.
1055 QUIC_FALLTHROUGH_INTENDED;
1056 case PING_FRAME:
1057 // Ping has no payload.
1058 break;
1059 case RST_STREAM_FRAME:
1060 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1061 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1062 return 0;
1063 }
1064 break;
1065 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001066 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1067 writer)) {
1068 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1069 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001070 return 0;
1071 }
1072 break;
1073 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001074 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001075 RaiseError(QUIC_INTERNAL_ERROR);
1076 QUIC_BUG << detailed_error();
1077 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001078 case WINDOW_UPDATE_FRAME:
1079 // Depending on whether there is a stream ID or not, will be either a
1080 // MAX STREAM DATA frame or a MAX DATA frame.
1081 if (frame.window_update_frame->stream_id ==
1082 QuicUtils::GetInvalidStreamId(transport_version())) {
1083 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1084 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1085 return 0;
1086 }
1087 } else {
1088 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1089 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1090 return 0;
1091 }
1092 }
1093 break;
1094 case BLOCKED_FRAME:
1095 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1096 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1097 return 0;
1098 }
1099 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001100 case MAX_STREAMS_FRAME:
1101 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001102 QUIC_BUG << "AppendMaxStreamsFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001103 return 0;
1104 }
1105 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001106 case STREAMS_BLOCKED_FRAME:
1107 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001108 QUIC_BUG << "AppendStreamsBlockedFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001109 return 0;
1110 }
1111 break;
1112 case NEW_CONNECTION_ID_FRAME:
1113 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1114 writer)) {
1115 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1116 return 0;
1117 }
1118 break;
1119 case RETIRE_CONNECTION_ID_FRAME:
1120 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1121 writer)) {
1122 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1123 << detailed_error();
1124 return 0;
1125 }
1126 break;
1127 case NEW_TOKEN_FRAME:
1128 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1129 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1130 return 0;
1131 }
1132 break;
1133 case STOP_SENDING_FRAME:
1134 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1135 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1136 return 0;
1137 }
1138 break;
1139 case PATH_CHALLENGE_FRAME:
1140 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1141 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1142 return 0;
1143 }
1144 break;
1145 case PATH_RESPONSE_FRAME:
1146 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1147 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1148 return 0;
1149 }
1150 break;
1151 case MESSAGE_FRAME:
1152 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1153 last_frame_in_packet, writer)) {
1154 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1155 return 0;
1156 }
1157 break;
1158 case CRYPTO_FRAME:
1159 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1160 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1161 return 0;
1162 }
1163 break;
fayang01062942020-01-22 07:23:23 -08001164 case HANDSHAKE_DONE_FRAME:
1165 // HANDSHAKE_DONE has no payload.
1166 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001167 default:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001168 set_detailed_error("Tried to append unknown frame type.");
dschinazi4a64ab62019-10-01 12:54:00 -07001169 RaiseError(QUIC_INVALID_FRAME_DATA);
1170 QUIC_BUG << "QUIC_INVALID_FRAME_DATA: " << frame.type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001171 return 0;
1172 }
1173 ++i;
1174 }
1175
1176 return writer->length();
1177}
1178
QUICHE teama6ef0a62019-03-07 20:34:33 -05001179// static
1180std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1181 const QuicPublicResetPacket& packet) {
1182 CryptoHandshakeMessage reset;
1183 reset.set_tag(kPRST);
1184 reset.SetValue(kRNON, packet.nonce_proof);
1185 if (packet.client_address.host().address_family() !=
1186 IpAddressFamily::IP_UNSPEC) {
1187 // packet.client_address is non-empty.
1188 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001189 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001190 if (serialized_address.empty()) {
1191 return nullptr;
1192 }
1193 reset.SetStringPiece(kCADR, serialized_address);
1194 }
1195 if (!packet.endpoint_id.empty()) {
1196 reset.SetStringPiece(kEPID, packet.endpoint_id);
1197 }
1198 const QuicData& reset_serialized = reset.GetSerialized();
1199
1200 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1201 reset_serialized.length();
1202 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001203 QuicDataWriter writer(len, buffer.get());
1204
1205 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1206 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1207 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1208 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1209 if (!writer.WriteUInt8(flags)) {
1210 return nullptr;
1211 }
1212
1213 if (!writer.WriteConnectionId(packet.connection_id)) {
1214 return nullptr;
1215 }
1216
1217 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1218 return nullptr;
1219 }
1220
vasilvv0fc587f2019-09-06 13:33:08 -07001221 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001222}
1223
1224// static
1225std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001226 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001227 QuicUint128 stateless_reset_token) {
1228 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1229 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1230 sizeof(stateless_reset_token);
1231 std::unique_ptr<char[]> buffer(new char[len]);
1232 QuicDataWriter writer(len, buffer.get());
1233
1234 uint8_t type = 0;
1235 type |= FLAGS_FIXED_BIT;
1236 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1237 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayang36825da2019-08-21 14:01:27 -07001238 type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001239
1240 // Append type byte.
1241 if (!writer.WriteUInt8(type)) {
1242 return nullptr;
1243 }
1244 // Append random bytes.
1245 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1246 kMinRandomBytesLengthInStatelessReset)) {
1247 return nullptr;
1248 }
1249
1250 // Append stateless reset token.
1251 if (!writer.WriteBytes(&stateless_reset_token,
1252 sizeof(stateless_reset_token))) {
1253 return nullptr;
1254 }
vasilvv0fc587f2019-09-06 13:33:08 -07001255 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001256}
1257
1258// static
1259std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001260 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001261 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001262 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001263 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001264 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001265 ParsedQuicVersionVector wire_versions = versions;
dschinazi5fc6d0c2019-11-26 16:22:05 -08001266 // Add a version reserved for negotiation as suggested by the
1267 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1268 if (wire_versions.empty()) {
1269 // Ensure that version negotiation packets we send have at least two
1270 // versions. This guarantees that, under all circumstances, all QUIC
1271 // packets we send are at least 14 bytes long.
1272 wire_versions = {QuicVersionReservedForNegotiation(),
1273 QuicVersionReservedForNegotiation()};
dschinazi1ac22cc2019-06-25 11:47:50 -07001274 } else {
dschinazi5fc6d0c2019-11-26 16:22:05 -08001275 // This is not uniformely distributed but is acceptable since no security
1276 // depends on this randomness.
1277 size_t version_index = 0;
1278 const bool disable_randomness =
1279 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1280 if (!disable_randomness) {
1281 version_index =
1282 QuicRandom::GetInstance()->RandUint64() % (wire_versions.size() + 1);
dschinazi1ac22cc2019-06-25 11:47:50 -07001283 }
dschinazi5fc6d0c2019-11-26 16:22:05 -08001284 wire_versions.insert(wire_versions.begin() + version_index,
1285 QuicVersionReservedForNegotiation());
dschinazi1ac22cc2019-06-25 11:47:50 -07001286 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001287 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001288 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001289 use_length_prefix, server_connection_id, client_connection_id,
1290 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001291 }
dschinazib417d602019-05-29 13:08:45 -07001292
1293 // The GQUIC encoding does not support encoding client connection IDs.
1294 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001295 // The GQUIC encoding does not support length-prefixed connection IDs.
1296 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001297
dschinazi1ac22cc2019-06-25 11:47:50 -07001298 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001299 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001300 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001301 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001302 QuicDataWriter writer(len, buffer.get());
1303
1304 uint8_t flags = static_cast<uint8_t>(
1305 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
QUICHE teama6ef0a62019-03-07 20:34:33 -05001306 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1307 if (!writer.WriteUInt8(flags)) {
1308 return nullptr;
1309 }
1310
dschinazi8ff74822019-05-28 16:37:20 -07001311 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001312 return nullptr;
1313 }
1314
dschinazi1ac22cc2019-06-25 11:47:50 -07001315 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001316 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001317 return nullptr;
1318 }
1319 }
1320
vasilvv0fc587f2019-09-06 13:33:08 -07001321 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001322}
1323
1324// static
1325std::unique_ptr<QuicEncryptedPacket>
1326QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001327 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001328 QuicConnectionId server_connection_id,
1329 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001330 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001331 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1332 << (use_length_prefix ? "" : "out")
1333 << " length prefix, server_connection_id "
1334 << server_connection_id << " client_connection_id "
1335 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001336 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001337 DCHECK(!versions.empty());
1338 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001339 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001340 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001341 if (use_length_prefix) {
1342 // When using length-prefixed connection IDs, packets carry two lengths
1343 // instead of one.
1344 len += kConnectionIdLengthSize;
1345 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001346 std::unique_ptr<char[]> buffer(new char[len]);
1347 QuicDataWriter writer(len, buffer.get());
1348
1349 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001350 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001351 if (!writer.WriteUInt8(type)) {
1352 return nullptr;
1353 }
1354
1355 if (!writer.WriteUInt32(0)) {
1356 return nullptr;
1357 }
1358
dschinazi48ac9192019-07-31 00:07:26 -07001359 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1360 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001361 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001362 }
1363
1364 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001365 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001366 return nullptr;
1367 }
1368 }
1369
vasilvv0fc587f2019-09-06 13:33:08 -07001370 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001371}
1372
1373bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1374 QuicDataReader reader(packet.data(), packet.length());
1375
1376 bool packet_has_ietf_packet_header = false;
1377 if (infer_packet_header_type_from_version_) {
1378 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001379 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001380 } else if (!reader.IsDoneReading()) {
1381 uint8_t type = reader.PeekByte();
1382 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1383 }
1384 if (packet_has_ietf_packet_header) {
1385 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1386 }
1387
1388 visitor_->OnPacket();
1389
1390 QuicPacketHeader header;
1391 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1392 DCHECK_NE("", detailed_error_);
1393 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1394 << detailed_error_;
1395 DCHECK_NE("", detailed_error_);
1396 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1397 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1398 }
1399
1400 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1401 // The visitor suppresses further processing of the packet.
1402 return true;
1403 }
1404
dschinazie0df3f72019-05-06 16:37:51 -07001405 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001406 if (perspective_ == Perspective::IS_CLIENT) {
1407 QUIC_DVLOG(1) << "Client received version negotiation packet";
1408 return ProcessVersionNegotiationPacket(&reader, header);
1409 } else {
1410 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1411 set_detailed_error("Server received version negotiation packet.");
1412 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1413 }
dschinazie0df3f72019-05-06 16:37:51 -07001414 }
1415
1416 if (header.version_flag && header.version != version_) {
1417 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001418 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001419 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1420 return true;
1421 }
1422 } else {
1423 // A client received a packet of a different version but that packet is
1424 // not a version negotiation packet. It is therefore invalid and dropped.
1425 QUIC_DLOG(ERROR) << "Client received unexpected version "
1426 << ParsedQuicVersionToString(header.version)
1427 << " instead of " << ParsedQuicVersionToString(version_);
1428 set_detailed_error("Client received unexpected version.");
1429 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001430 }
1431 }
1432
1433 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001434 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001435 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001436 } else if (header.reset_flag) {
1437 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001438 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001439 // The optimized decryption algorithm implementations run faster when
1440 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001441 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001442 if (packet_has_ietf_packet_header) {
1443 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001444 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001445 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001446 rv = ProcessDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001447 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001448 }
1449 } else {
1450 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1451 if (packet_has_ietf_packet_header) {
1452 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1453 packet.length());
1454 } else {
1455 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1456 packet.length());
1457 }
1458 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001459 << "than kMaxIncomingPacketSize. packet size:"
1460 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001461 }
1462 return rv;
1463}
1464
1465bool QuicFramer::ProcessVersionNegotiationPacket(
1466 QuicDataReader* reader,
1467 const QuicPacketHeader& header) {
1468 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1469
QUICHE team2252b702019-05-14 23:55:14 -04001470 QuicVersionNegotiationPacket packet(
1471 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001472 // Try reading at least once to raise error if the packet is invalid.
1473 do {
1474 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001475 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001476 set_detailed_error("Unable to read supported version in negotiation.");
1477 RecordDroppedPacketReason(
1478 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1479 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1480 }
nharper4fd11052019-06-04 14:23:22 -07001481 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1482 if (parsed_version != UnsupportedQuicVersion()) {
1483 packet.versions.push_back(parsed_version);
1484 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001485 } while (!reader->IsDoneReading());
1486
dschinazi5a354c92019-05-09 12:18:53 -07001487 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1488 << ParsedQuicVersionVectorToString(packet.versions);
1489
QUICHE teama6ef0a62019-03-07 20:34:33 -05001490 visitor_->OnVersionNegotiationPacket(packet);
1491 return true;
1492}
1493
dschinazi244f6dc2019-05-06 15:45:16 -07001494bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1495 const QuicPacketHeader& header) {
1496 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1497
dschinazi278efae2020-01-28 17:03:09 -08001498 if (version_.HasRetryIntegrityTag()) {
1499 DCHECK(version_.HasLengthPrefixedConnectionIds()) << version_;
1500 const size_t bytes_remaining = reader->BytesRemaining();
1501 if (bytes_remaining <= kRetryIntegrityTagLength) {
1502 set_detailed_error("Retry packet too short to parse integrity tag.");
1503 return false;
1504 }
1505 const size_t retry_token_length =
1506 bytes_remaining - kRetryIntegrityTagLength;
1507 DCHECK_GT(retry_token_length, 0u);
1508 quiche::QuicheStringPiece retry_token;
1509 if (!reader->ReadStringPiece(&retry_token, retry_token_length)) {
1510 set_detailed_error("Failed to read retry token.");
1511 return false;
1512 }
1513 quiche::QuicheStringPiece retry_without_tag =
1514 reader->PreviouslyReadPayload();
1515 quiche::QuicheStringPiece integrity_tag = reader->ReadRemainingPayload();
1516 DCHECK_EQ(integrity_tag.length(), kRetryIntegrityTagLength);
1517 visitor_->OnRetryPacket(EmptyQuicConnectionId(),
1518 header.source_connection_id, retry_token,
1519 integrity_tag, retry_without_tag);
1520 return true;
1521 }
1522
dschinazi244f6dc2019-05-06 15:45:16 -07001523 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001524 if (version_.HasLengthPrefixedConnectionIds()) {
1525 // Parse Original Destination Connection ID.
1526 if (!reader->ReadLengthPrefixedConnectionId(
1527 &original_destination_connection_id)) {
1528 set_detailed_error("Unable to read Original Destination ConnectionId.");
1529 return false;
1530 }
1531 } else {
1532 // Parse Original Destination Connection ID Length.
1533 uint8_t odcil = header.type_byte & 0xf;
1534 if (odcil != 0) {
1535 odcil += kConnectionIdLengthAdjustment;
1536 }
1537
1538 // Parse Original Destination Connection ID.
1539 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1540 set_detailed_error("Unable to read Original Destination ConnectionId.");
1541 return false;
1542 }
dschinazi244f6dc2019-05-06 15:45:16 -07001543 }
1544
dschinazib953d022019-08-01 18:05:58 -07001545 if (!QuicUtils::IsConnectionIdValidForVersion(
1546 original_destination_connection_id, transport_version())) {
1547 set_detailed_error(
1548 "Received Original Destination ConnectionId with invalid length.");
1549 return false;
1550 }
1551
dmcardlecf0bfcf2019-12-13 08:08:21 -08001552 quiche::QuicheStringPiece retry_token = reader->ReadRemainingPayload();
dschinazi244f6dc2019-05-06 15:45:16 -07001553 visitor_->OnRetryPacket(original_destination_connection_id,
dschinazi278efae2020-01-28 17:03:09 -08001554 header.source_connection_id, retry_token,
1555 /*retry_integrity_tag=*/quiche::QuicheStringPiece(),
1556 /*retry_without_tag=*/quiche::QuicheStringPiece());
dschinazi244f6dc2019-05-06 15:45:16 -07001557 return true;
1558}
1559
QUICHE teama6ef0a62019-03-07 20:34:33 -05001560// Seeks the current packet to check for a coalesced packet at the end.
1561// If the IETF length field only spans part of the outer packet,
1562// then there is a coalesced packet after this one.
1563void QuicFramer::MaybeProcessCoalescedPacket(
1564 const QuicDataReader& encrypted_reader,
1565 uint64_t remaining_bytes_length,
1566 const QuicPacketHeader& header) {
1567 if (header.remaining_packet_length >= remaining_bytes_length) {
1568 // There is no coalesced packet.
1569 return;
1570 }
1571
dmcardlecf0bfcf2019-12-13 08:08:21 -08001572 quiche::QuicheStringPiece remaining_data =
1573 encrypted_reader.PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001574 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1575
1576 const char* coalesced_data =
1577 remaining_data.data() + header.remaining_packet_length;
1578 uint64_t coalesced_data_length =
1579 remaining_bytes_length - header.remaining_packet_length;
1580 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1581
1582 QuicPacketHeader coalesced_header;
1583 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1584 QUIC_PEER_BUG << ENDPOINT
1585 << "Failed to parse received coalesced header of length "
1586 << coalesced_data_length << ": "
dmcardlecf0bfcf2019-12-13 08:08:21 -08001587 << quiche::QuicheTextUtils::HexEncode(coalesced_data,
1588 coalesced_data_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -05001589 << " previous header was " << header;
1590 return;
1591 }
1592
1593 if (coalesced_header.destination_connection_id !=
1594 header.destination_connection_id ||
1595 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1596 coalesced_header.version != header.version)) {
1597 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1598 << coalesced_header << " previous header was " << header;
1599 return;
1600 }
1601
1602 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1603 /*owns_buffer=*/false);
1604 visitor_->OnCoalescedPacket(coalesced_packet);
1605}
1606
1607bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1608 QuicPacketHeader* header) {
1609 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1610 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1611 (header->long_packet_type != INITIAL &&
1612 header->long_packet_type != HANDSHAKE &&
1613 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1614 return true;
1615 }
1616 header->length_length = encrypted_reader->PeekVarInt62Length();
1617 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1618 set_detailed_error("Unable to read long header payload length.");
1619 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1620 }
1621 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1622 if (header->remaining_packet_length > remaining_bytes_length) {
1623 set_detailed_error("Long header payload length longer than packet.");
1624 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1625 }
1626
1627 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1628 *header);
1629
1630 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1631 set_detailed_error("Length TruncateRemaining failed.");
1632 QUIC_BUG << "Length TruncateRemaining failed.";
1633 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1634 }
1635 return true;
1636}
1637
1638bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1639 QuicPacketHeader* header,
1640 const QuicEncryptedPacket& packet,
1641 char* decrypted_buffer,
1642 size_t buffer_length) {
1643 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1644 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001645 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1646 header->remaining_packet_length = 0;
1647 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1648 perspective_ == Perspective::IS_CLIENT) {
1649 // Peek possible stateless reset token. Will only be used on decryption
1650 // failure.
dmcardlecf0bfcf2019-12-13 08:08:21 -08001651 quiche::QuicheStringPiece remaining =
1652 encrypted_reader->PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001653 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1654 header->has_possible_stateless_reset_token = true;
1655 memcpy(&header->possible_stateless_reset_token,
1656 &remaining.data()[remaining.length() -
1657 sizeof(header->possible_stateless_reset_token)],
1658 sizeof(header->possible_stateless_reset_token));
1659 }
1660 }
1661
QUICHE teama6ef0a62019-03-07 20:34:33 -05001662 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1663 return false;
1664 }
1665
dmcardlecf0bfcf2019-12-13 08:08:21 -08001666 quiche::QuicheStringPiece associated_data;
nharper55fa6132019-05-07 19:37:21 -07001667 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001668 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1669 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001670 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1671 header->long_packet_type == INITIAL ||
1672 header->long_packet_type == HANDSHAKE ||
1673 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001674 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001675 QuicPacketNumber base_packet_number;
1676 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001677 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1678 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1679 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1680 }
1681 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001682 } else {
1683 base_packet_number = largest_packet_number_;
1684 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001685 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001686 bool hp_removal_failed = false;
1687 if (version_.HasHeaderProtection()) {
1688 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1689 &full_packet_number, &ad_storage)) {
1690 hp_removal_failed = true;
1691 }
dmcardlecf0bfcf2019-12-13 08:08:21 -08001692 associated_data =
1693 quiche::QuicheStringPiece(ad_storage.data(), ad_storage.size());
nharper55fa6132019-05-07 19:37:21 -07001694 } else if (!ProcessAndCalculatePacketNumber(
1695 encrypted_reader, header->packet_number_length,
1696 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001697 set_detailed_error("Unable to read packet number.");
1698 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1699 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1700 }
1701
nharper55fa6132019-05-07 19:37:21 -07001702 if (hp_removal_failed ||
1703 !IsValidFullPacketNumber(full_packet_number, transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001704 if (IsIetfStatelessResetPacket(*header)) {
1705 // This is a stateless reset packet.
1706 QuicIetfStatelessResetPacket packet(
1707 *header, header->possible_stateless_reset_token);
1708 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1709 return true;
1710 }
nharper55fa6132019-05-07 19:37:21 -07001711 if (hp_removal_failed) {
wub13d75452019-11-05 07:24:56 -08001712 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1713 const bool has_decryption_key = decrypter_[decryption_level] != nullptr;
1714 visitor_->OnUndecryptablePacket(
1715 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1716 decryption_level, has_decryption_key);
nharper55fa6132019-05-07 19:37:21 -07001717 set_detailed_error("Unable to decrypt header protection.");
1718 return RaiseError(QUIC_DECRYPTION_FAILURE);
1719 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001720 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1721 set_detailed_error("packet numbers cannot be 0.");
1722 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1723 }
1724 header->packet_number = QuicPacketNumber(full_packet_number);
1725 }
1726
1727 // A nonce should only present in SHLO from the server to the client when
1728 // using QUIC crypto.
1729 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1730 header->long_packet_type == ZERO_RTT_PROTECTED &&
1731 perspective_ == Perspective::IS_CLIENT &&
1732 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1733 if (!encrypted_reader->ReadBytes(
1734 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1735 last_nonce_.size())) {
1736 set_detailed_error("Unable to read nonce.");
1737 RecordDroppedPacketReason(
1738 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1739 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1740 }
1741
1742 header->nonce = &last_nonce_;
1743 } else {
1744 header->nonce = nullptr;
1745 }
1746
1747 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1748 set_detailed_error(
1749 "Visitor asked to stop processing of unauthenticated header.");
1750 return false;
1751 }
1752
dmcardlecf0bfcf2019-12-13 08:08:21 -08001753 quiche::QuicheStringPiece encrypted =
1754 encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001755 if (!version_.HasHeaderProtection()) {
1756 associated_data = GetAssociatedDataFromEncryptedPacket(
1757 version_.transport_version, packet,
1758 GetIncludedDestinationConnectionIdLength(*header),
1759 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1760 header->nonce != nullptr, header->packet_number_length,
1761 header->retry_token_length_length, header->retry_token.length(),
1762 header->length_length);
1763 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001764
1765 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001766 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001767 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001768 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001769 if (IsIetfStatelessResetPacket(*header)) {
1770 // This is a stateless reset packet.
1771 QuicIetfStatelessResetPacket packet(
1772 *header, header->possible_stateless_reset_token);
1773 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1774 return true;
1775 }
wub13d75452019-11-05 07:24:56 -08001776 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1777 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1778 decrypter_[decryption_level] != nullptr;
1779 visitor_->OnUndecryptablePacket(
1780 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1781 has_decryption_key);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001782 set_detailed_error("Unable to decrypt payload.");
1783 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1784 return RaiseError(QUIC_DECRYPTION_FAILURE);
1785 }
1786 QuicDataReader reader(decrypted_buffer, decrypted_length);
1787
1788 // Update the largest packet number after we have decrypted the packet
1789 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001790 if (supports_multiple_packet_number_spaces_) {
1791 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1792 decrypted_level)]
1793 .UpdateMax(header->packet_number);
1794 } else {
1795 largest_packet_number_.UpdateMax(header->packet_number);
1796 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001797
1798 if (!visitor_->OnPacketHeader(*header)) {
1799 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1800 // The visitor suppresses further processing of the packet.
1801 return true;
1802 }
1803
dschinazie8d7fa72019-04-05 14:44:40 -07001804 if (packet.length() > kMaxIncomingPacketSize) {
1805 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001806 return RaiseError(QUIC_PACKET_TOO_LARGE);
1807 }
1808
1809 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001810 if (VersionHasIetfQuicFrames(version_.transport_version)) {
fkastenholza3660102019-08-28 05:19:24 -07001811 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001812 if (!ProcessIetfFrameData(&reader, *header)) {
fkastenholza3660102019-08-28 05:19:24 -07001813 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001814 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1815 DCHECK_NE("", detailed_error_);
1816 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1817 << detailed_error_;
1818 return false;
1819 }
fkastenholza3660102019-08-28 05:19:24 -07001820 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001821 } else {
1822 if (!ProcessFrameData(&reader, *header)) {
1823 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1824 DCHECK_NE("", detailed_error_);
1825 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1826 << detailed_error_;
1827 return false;
1828 }
1829 }
1830
1831 visitor_->OnPacketComplete();
1832 return true;
1833}
1834
1835bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1836 QuicPacketHeader* header,
1837 const QuicEncryptedPacket& packet,
1838 char* decrypted_buffer,
1839 size_t buffer_length) {
1840 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1841 DCHECK_NE("", detailed_error_);
1842 QUIC_DVLOG(1)
1843 << ENDPOINT
1844 << "Unable to process packet header. Stopping parsing. Error: "
1845 << detailed_error_;
1846 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1847 return false;
1848 }
1849
dmcardlecf0bfcf2019-12-13 08:08:21 -08001850 quiche::QuicheStringPiece encrypted =
1851 encrypted_reader->ReadRemainingPayload();
1852 quiche::QuicheStringPiece associated_data =
1853 GetAssociatedDataFromEncryptedPacket(
1854 version_.transport_version, packet,
1855 GetIncludedDestinationConnectionIdLength(*header),
1856 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1857 header->nonce != nullptr, header->packet_number_length,
1858 header->retry_token_length_length, header->retry_token.length(),
1859 header->length_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001860
1861 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001862 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001863 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001864 buffer_length, &decrypted_length, &decrypted_level)) {
wub13d75452019-11-05 07:24:56 -08001865 const EncryptionLevel decryption_level = decrypter_level_;
1866 // This version uses trial decryption so we always report to our visitor
1867 // that we are not certain we have the correct decryption key.
1868 const bool has_decryption_key = false;
1869 visitor_->OnUndecryptablePacket(
1870 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1871 has_decryption_key);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001872 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1873 set_detailed_error("Unable to decrypt payload.");
1874 return RaiseError(QUIC_DECRYPTION_FAILURE);
1875 }
1876
1877 QuicDataReader reader(decrypted_buffer, decrypted_length);
1878
1879 // Update the largest packet number after we have decrypted the packet
1880 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001881 if (supports_multiple_packet_number_spaces_) {
1882 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1883 decrypted_level)]
1884 .UpdateMax(header->packet_number);
1885 } else {
1886 largest_packet_number_.UpdateMax(header->packet_number);
1887 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001888
1889 if (!visitor_->OnPacketHeader(*header)) {
1890 // The visitor suppresses further processing of the packet.
1891 return true;
1892 }
1893
dschinazie8d7fa72019-04-05 14:44:40 -07001894 if (packet.length() > kMaxIncomingPacketSize) {
1895 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001896 return RaiseError(QUIC_PACKET_TOO_LARGE);
1897 }
1898
1899 // Handle the payload.
1900 if (!ProcessFrameData(&reader, *header)) {
1901 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1902 DCHECK_NE("", detailed_error_);
1903 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1904 << detailed_error_;
1905 return false;
1906 }
1907
1908 visitor_->OnPacketComplete();
1909 return true;
1910}
1911
1912bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1913 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001914 QuicPublicResetPacket packet(
1915 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001916
1917 std::unique_ptr<CryptoHandshakeMessage> reset(
1918 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
wub07a2b072019-10-24 11:23:20 -07001919 if (!reset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001920 set_detailed_error("Unable to read reset message.");
1921 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1922 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1923 }
1924 if (reset->tag() != kPRST) {
1925 set_detailed_error("Incorrect message tag.");
1926 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1927 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1928 }
1929
1930 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
1931 set_detailed_error("Unable to read nonce proof.");
1932 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1933 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1934 }
1935 // TODO(satyamshekhar): validate nonce to protect against DoS.
1936
dmcardlecf0bfcf2019-12-13 08:08:21 -08001937 quiche::QuicheStringPiece address;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001938 if (reset->GetStringPiece(kCADR, &address)) {
1939 QuicSocketAddressCoder address_coder;
1940 if (address_coder.Decode(address.data(), address.length())) {
1941 packet.client_address =
1942 QuicSocketAddress(address_coder.ip(), address_coder.port());
1943 }
1944 }
1945
dmcardlecf0bfcf2019-12-13 08:08:21 -08001946 quiche::QuicheStringPiece endpoint_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001947 if (perspective_ == Perspective::IS_CLIENT &&
1948 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07001949 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001950 packet.endpoint_id += '\0';
1951 }
1952
1953 visitor_->OnPublicResetPacket(packet);
1954 return true;
1955}
1956
1957bool QuicFramer::IsIetfStatelessResetPacket(
1958 const QuicPacketHeader& header) const {
1959 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
1960 perspective_ != Perspective::IS_CLIENT)
1961 << "has_possible_stateless_reset_token can only be true at client side.";
1962 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
1963 header.has_possible_stateless_reset_token &&
1964 visitor_->IsValidStatelessResetToken(
1965 header.possible_stateless_reset_token);
1966}
1967
1968bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
1969 return encrypter_[level] != nullptr;
1970}
1971
1972bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
1973 QuicDataWriter* writer,
1974 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07001975 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001976 return AppendIetfPacketHeader(header, writer, length_field_offset);
1977 }
1978 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
1979 uint8_t public_flags = 0;
1980 if (header.reset_flag) {
1981 public_flags |= PACKET_PUBLIC_FLAGS_RST;
1982 }
1983 if (header.version_flag) {
1984 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
1985 }
1986
1987 public_flags |= GetPacketNumberFlags(header.packet_number_length)
1988 << kPublicHeaderSequenceNumberShift;
1989
1990 if (header.nonce != nullptr) {
1991 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
1992 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
1993 }
QUICHE team2252b702019-05-14 23:55:14 -04001994
dschinazi7b9278c2019-05-20 07:36:21 -07001995 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04001996 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07001997 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04001998 GetServerConnectionIdIncludedAsSender(header, perspective_);
1999 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002000 GetClientConnectionIdIncludedAsSender(header, perspective_))
2001 << ENDPOINT << ParsedQuicVersionToString(version_)
2002 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002003
dschinazi7b9278c2019-05-20 07:36:21 -07002004 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002005 case CONNECTION_ID_ABSENT:
2006 if (!writer->WriteUInt8(public_flags |
2007 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2008 return false;
2009 }
2010 break;
2011 case CONNECTION_ID_PRESENT:
2012 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002013 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002014 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002015 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002016 << QuicVersionToString(transport_version());
2017
2018 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2019 if (perspective_ == Perspective::IS_CLIENT) {
2020 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2021 }
2022 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002023 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002024 return false;
2025 }
2026 break;
2027 }
dschinazi7b9278c2019-05-20 07:36:21 -07002028 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002029
2030 if (header.version_flag) {
2031 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2032 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002033 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002034 return false;
2035 }
2036
2037 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2038 << QuicVersionLabelToString(version_label) << "'";
2039 }
2040
2041 if (header.nonce != nullptr &&
2042 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2043 return false;
2044 }
2045
2046 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2047 writer)) {
2048 return false;
2049 }
2050
2051 return true;
2052}
2053
2054bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2055 QuicDataWriter* writer) {
2056 uint8_t type = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002057 if (header.version_flag) {
2058 type = static_cast<uint8_t>(
fayang36825da2019-08-21 14:01:27 -07002059 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2060 LongHeaderTypeToOnWireValue(header.long_packet_type) |
2061 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002062 } else {
fayang36825da2019-08-21 14:01:27 -07002063 type = static_cast<uint8_t>(
2064 FLAGS_FIXED_BIT |
2065 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002066 }
2067 return writer->WriteUInt8(type);
2068}
2069
2070bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2071 QuicDataWriter* writer,
2072 size_t* length_field_offset) {
2073 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002074 QuicConnectionId server_connection_id =
2075 GetServerConnectionIdAsSender(header, perspective_);
2076 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2077 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002078 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002079 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002080 << QuicVersionToString(transport_version());
2081 if (!AppendIetfHeaderTypeByte(header, writer)) {
2082 return false;
2083 }
2084
2085 if (header.version_flag) {
dschinaziecad9642019-10-01 10:44:17 -07002086 DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type)
2087 << "QuicFramer::AppendIetfPacketHeader does not support sending "
2088 "version negotiation packets, use "
2089 "QuicFramer::BuildVersionNegotiationPacket instead "
2090 << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002091 // Append version for long header.
2092 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002093 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002094 return false;
2095 }
2096 }
2097
2098 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002099 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002100 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002101 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2102 ? header.destination_connection_id
2103 : EmptyQuicConnectionId(),
2104 header.source_connection_id_included != CONNECTION_ID_ABSENT
2105 ? header.source_connection_id
2106 : EmptyQuicConnectionId(),
2107 writer)) {
2108 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002109 }
dschinazi1f485a12019-05-13 11:57:01 -07002110
dschinazi7b9278c2019-05-20 07:36:21 -07002111 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002112 if (version_.SupportsClientConnectionIds()) {
2113 last_serialized_client_connection_id_ =
2114 GetClientConnectionIdAsSender(header, perspective_);
2115 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002116
dschinaziecad9642019-10-01 10:44:17 -07002117 // TODO(b/141924462) Remove this QUIC_BUG once we do support sending RETRY.
2118 QUIC_BUG_IF(header.version_flag && header.long_packet_type == RETRY)
2119 << "Sending IETF RETRY packets is not currently supported " << header;
2120
QUICHE teama6ef0a62019-03-07 20:34:33 -05002121 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2122 header.version_flag) {
2123 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002124 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2125 header.retry_token_length_length)
2126 << ENDPOINT << ParsedQuicVersionToString(version_)
2127 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002128 // Write retry token length.
2129 if (!writer->WriteVarInt62(header.retry_token.length(),
2130 header.retry_token_length_length)) {
2131 return false;
2132 }
2133 // Write retry token.
2134 if (!header.retry_token.empty() &&
2135 !writer->WriteStringPiece(header.retry_token)) {
2136 return false;
2137 }
2138 }
2139 if (length_field_offset != nullptr) {
2140 *length_field_offset = writer->length();
2141 }
2142 // Add fake length to reserve two bytes to add length in later.
2143 writer->WriteVarInt62(256);
2144 } else if (length_field_offset != nullptr) {
2145 *length_field_offset = 0;
2146 }
2147
2148 // Append packet number.
2149 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2150 writer)) {
2151 return false;
2152 }
nharper55fa6132019-05-07 19:37:21 -07002153 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002154
2155 if (!header.version_flag) {
2156 return true;
2157 }
2158
2159 if (header.nonce != nullptr) {
2160 DCHECK(header.version_flag);
2161 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2162 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2163 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2164 return false;
2165 }
2166 }
2167
2168 return true;
2169}
2170
2171const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2172 uint32_t time_delta_us) {
2173 // The new time_delta might have wrapped to the next epoch, or it
2174 // might have reverse wrapped to the previous epoch, or it might
2175 // remain in the same epoch. Select the time closest to the previous
2176 // time.
2177 //
2178 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2179 // microseconds.
2180 const uint64_t epoch_delta = UINT64_C(1) << 32;
2181 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2182 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2183 uint64_t prev_epoch = epoch - epoch_delta;
2184 uint64_t next_epoch = epoch + epoch_delta;
2185
2186 uint64_t time = ClosestTo(
2187 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2188 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2189 next_epoch + time_delta_us));
2190
2191 return QuicTime::Delta::FromMicroseconds(time);
2192}
2193
2194uint64_t QuicFramer::CalculatePacketNumberFromWire(
2195 QuicPacketNumberLength packet_number_length,
2196 QuicPacketNumber base_packet_number,
2197 uint64_t packet_number) const {
2198 // The new packet number might have wrapped to the next epoch, or
2199 // it might have reverse wrapped to the previous epoch, or it might
2200 // remain in the same epoch. Select the packet number closest to the
2201 // next expected packet number, the previous packet number plus 1.
2202
2203 // epoch_delta is the delta between epochs the packet number was serialized
2204 // with, so the correct value is likely the same epoch as the last sequence
2205 // number or an adjacent epoch.
2206 if (!base_packet_number.IsInitialized()) {
2207 return packet_number;
2208 }
2209 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2210 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2211 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2212 uint64_t prev_epoch = epoch - epoch_delta;
2213 uint64_t next_epoch = epoch + epoch_delta;
2214
2215 return ClosestTo(next_packet_number, epoch + packet_number,
2216 ClosestTo(next_packet_number, prev_epoch + packet_number,
2217 next_epoch + packet_number));
2218}
2219
2220bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2221 bool packet_has_ietf_packet_header,
2222 QuicPacketHeader* header) {
2223 if (packet_has_ietf_packet_header) {
2224 return ProcessIetfPacketHeader(reader, header);
2225 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002226 uint8_t public_flags;
2227 if (!reader->ReadBytes(&public_flags, 1)) {
2228 set_detailed_error("Unable to read public flags.");
2229 return false;
2230 }
2231
2232 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2233 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2234
2235 if (validate_flags_ && !header->version_flag &&
2236 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2237 set_detailed_error("Illegal public flags value.");
2238 return false;
2239 }
2240
2241 if (header->reset_flag && header->version_flag) {
2242 set_detailed_error("Got version flag in reset packet");
2243 return false;
2244 }
2245
QUICHE team2252b702019-05-14 23:55:14 -04002246 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2247 QuicConnectionIdIncluded* header_connection_id_included =
2248 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002249 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002250 header_connection_id = &header->source_connection_id;
2251 header_connection_id_included = &header->source_connection_id_included;
2252 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002253 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2254 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002255 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002256 kQuicDefaultConnectionIdLength)) {
2257 set_detailed_error("Unable to read ConnectionId.");
2258 return false;
2259 }
QUICHE team2252b702019-05-14 23:55:14 -04002260 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002261 break;
2262 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002263 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002264 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002265 break;
2266 }
2267
2268 header->packet_number_length = ReadSequenceNumberLength(
2269 public_flags >> kPublicHeaderSequenceNumberShift);
2270
2271 // Read the version only if the packet is from the client.
2272 // version flag from the server means version negotiation packet.
2273 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2274 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002275 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002276 set_detailed_error("Unable to read protocol version.");
2277 return false;
2278 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002279 // If the version from the new packet is the same as the version of this
2280 // framer, then the public flags should be set to something we understand.
2281 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002282 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2283 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2284 set_detailed_error("Illegal public flags value.");
2285 return false;
2286 }
2287 header->version = version;
2288 }
2289
2290 // A nonce should only be present in packets from the server to the client,
2291 // which are neither version negotiation nor public reset packets.
2292 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2293 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2294 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2295 // The nonce flag from a client is ignored and is assumed to be an older
2296 // client indicating an eight-byte connection ID.
2297 perspective_ == Perspective::IS_CLIENT) {
2298 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2299 last_nonce_.size())) {
2300 set_detailed_error("Unable to read nonce.");
2301 return false;
2302 }
2303 header->nonce = &last_nonce_;
2304 } else {
2305 header->nonce = nullptr;
2306 }
2307
2308 return true;
2309}
2310
2311// static
2312QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05002313 QuicPacketNumber packet_number) {
2314 DCHECK(packet_number.IsInitialized());
2315 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2316 return PACKET_1BYTE_PACKET_NUMBER;
2317 } else if (packet_number <
2318 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2319 return PACKET_2BYTE_PACKET_NUMBER;
2320 } else if (packet_number <
2321 QuicPacketNumber(UINT64_C(1)
2322 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2323 return PACKET_4BYTE_PACKET_NUMBER;
2324 } else {
2325 return PACKET_6BYTE_PACKET_NUMBER;
2326 }
2327}
2328
2329// static
2330uint8_t QuicFramer::GetPacketNumberFlags(
2331 QuicPacketNumberLength packet_number_length) {
2332 switch (packet_number_length) {
2333 case PACKET_1BYTE_PACKET_NUMBER:
2334 return PACKET_FLAGS_1BYTE_PACKET;
2335 case PACKET_2BYTE_PACKET_NUMBER:
2336 return PACKET_FLAGS_2BYTE_PACKET;
2337 case PACKET_4BYTE_PACKET_NUMBER:
2338 return PACKET_FLAGS_4BYTE_PACKET;
2339 case PACKET_6BYTE_PACKET_NUMBER:
2340 case PACKET_8BYTE_PACKET_NUMBER:
2341 return PACKET_FLAGS_8BYTE_PACKET;
2342 default:
2343 QUIC_BUG << "Unreachable case statement.";
2344 return PACKET_FLAGS_8BYTE_PACKET;
2345 }
2346}
2347
2348// static
2349QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2350 const QuicAckFrame& frame) {
2351 AckFrameInfo new_ack_info;
2352 if (frame.packets.Empty()) {
2353 return new_ack_info;
2354 }
2355 // The first block is the last interval. It isn't encoded with the gap-length
2356 // encoding, so skip it.
2357 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2358 auto itr = frame.packets.rbegin();
2359 QuicPacketNumber previous_start = itr->min();
wub13d75452019-11-05 07:24:56 -08002360 new_ack_info.max_block_length = itr->Length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002361 ++itr;
2362
2363 // Don't do any more work after getting information for 256 ACK blocks; any
2364 // more can't be encoded anyway.
2365 for (; itr != frame.packets.rend() &&
2366 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2367 previous_start = itr->min(), ++itr) {
2368 const auto& interval = *itr;
2369 const QuicPacketCount total_gap = previous_start - interval.max();
2370 new_ack_info.num_ack_blocks +=
2371 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2372 std::numeric_limits<uint8_t>::max();
wub13d75452019-11-05 07:24:56 -08002373 new_ack_info.max_block_length =
2374 std::max(new_ack_info.max_block_length, interval.Length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002375 }
2376 return new_ack_info;
2377}
2378
2379bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2380 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002381 QuicPacketNumber base_packet_number;
2382 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002383 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2384 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2385 set_detailed_error("Unable to determine packet number space.");
2386 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2387 }
2388 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002389 } else {
2390 base_packet_number = largest_packet_number_;
2391 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002392 uint64_t full_packet_number;
2393 if (!ProcessAndCalculatePacketNumber(
2394 encrypted_reader, header->packet_number_length, base_packet_number,
2395 &full_packet_number)) {
2396 set_detailed_error("Unable to read packet number.");
2397 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2398 }
2399
2400 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2401 set_detailed_error("packet numbers cannot be 0.");
2402 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2403 }
2404 header->packet_number = QuicPacketNumber(full_packet_number);
2405
2406 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2407 set_detailed_error(
2408 "Visitor asked to stop processing of unauthenticated header.");
2409 return false;
2410 }
nharper3f283562019-05-02 16:37:12 -07002411 // The function we are in is called because the framer believes that it is
2412 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2413 // type. Usually, the framer makes that decision based on the framer's
2414 // version, but when the framer is used with Perspective::IS_SERVER, then
2415 // before version negotiation is complete (specifically, before
2416 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2417 // the type byte of the packet.
2418 //
2419 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2420 // to use the IETF packet header type. If that's the case and we're in this
2421 // function, then the packet received is invalid: the framer was expecting an
2422 // IETF packet header and didn't get one.
2423 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002424 set_detailed_error("Invalid public header type for expected version.");
2425 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2426 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002427 return true;
2428}
2429
2430bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2431 QuicPacketHeader* header) {
2432 uint8_t type;
2433 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002434 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002435 return false;
2436 }
dschinazi244f6dc2019-05-06 15:45:16 -07002437 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002438 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002439 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002440 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2441 // Version is always present in long headers.
2442 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002443 // In versions that do not support client connection IDs, we mark the
2444 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002445 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002446 (perspective_ == Perspective::IS_SERVER ||
2447 version_.SupportsClientConnectionIds())
2448 ? CONNECTION_ID_PRESENT
2449 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002450 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002451 (perspective_ == Perspective::IS_CLIENT ||
2452 version_.SupportsClientConnectionIds())
2453 ? CONNECTION_ID_PRESENT
2454 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002455 // Read version tag.
2456 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002457 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002458 set_detailed_error("Unable to read protocol version.");
2459 return false;
2460 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002461 if (!version_label) {
2462 // Version label is 0 indicating this is a version negotiation packet.
2463 header->long_packet_type = VERSION_NEGOTIATION;
2464 } else {
2465 header->version = ParseQuicVersionLabel(version_label);
2466 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayang36825da2019-08-21 14:01:27 -07002467 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002468 set_detailed_error("Fixed bit is 0 in long header.");
2469 return false;
2470 }
fayang36825da2019-08-21 14:01:27 -07002471 if (!GetLongHeaderType(type, &header->long_packet_type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002472 set_detailed_error("Illegal long header type value.");
2473 return false;
2474 }
dschinazi244f6dc2019-05-06 15:45:16 -07002475 if (header->long_packet_type == RETRY) {
2476 if (!version().SupportsRetry()) {
2477 set_detailed_error("RETRY not supported in this version.");
2478 return false;
2479 }
2480 if (perspective_ == Perspective::IS_SERVER) {
2481 set_detailed_error("Client-initiated RETRY is invalid.");
2482 return false;
2483 }
nharper55fa6132019-05-07 19:37:21 -07002484 } else if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002485 header->packet_number_length = GetLongHeaderPacketNumberLength(type);
nharper2ceb97c2019-04-19 11:38:59 -07002486 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002487 }
2488 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002489
2490 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2491 << QuicUtils::QuicLongHeaderTypetoString(
2492 header->long_packet_type);
2493 return true;
2494 }
2495
2496 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2497 // Version is not present in short headers.
2498 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002499 // In versions that do not support client connection IDs, the client will not
2500 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002501 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002502 (perspective_ == Perspective::IS_SERVER ||
2503 version_.SupportsClientConnectionIds())
2504 ? CONNECTION_ID_PRESENT
2505 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002506 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayang36825da2019-08-21 14:01:27 -07002507 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002508 set_detailed_error("Fixed bit is 0 in short header.");
2509 return false;
2510 }
dschinazidc770fc2020-01-13 15:42:41 -08002511 if (!version_.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002512 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002513 }
2514 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2515 return true;
2516}
2517
fayang40315542019-05-09 09:19:09 -07002518// static
2519bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2520 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002521 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002522 return false;
2523 }
fayang40315542019-05-09 09:19:09 -07002524 return true;
2525}
2526
2527// static
fayangccbab732019-05-13 10:11:25 -07002528bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2529 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002530 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002531 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002532 bool should_update_expected_server_connection_id_length,
2533 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002534 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002535 uint8_t* source_connection_id_length,
2536 std::string* detailed_error) {
2537 uint8_t connection_id_lengths_byte;
2538 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2539 *detailed_error = "Unable to read ConnectionId length.";
2540 return false;
2541 }
fayang40315542019-05-09 09:19:09 -07002542 uint8_t dcil =
2543 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2544 if (dcil != 0) {
2545 dcil += kConnectionIdLengthAdjustment;
2546 }
fayang40315542019-05-09 09:19:09 -07002547 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2548 if (scil != 0) {
2549 scil += kConnectionIdLengthAdjustment;
2550 }
dschinazi334f0232019-05-29 16:08:53 -07002551 if (should_update_expected_server_connection_id_length) {
2552 uint8_t server_connection_id_length =
2553 perspective == Perspective::IS_SERVER ? dcil : scil;
2554 if (*expected_server_connection_id_length != server_connection_id_length) {
2555 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2556 << static_cast<int>(*expected_server_connection_id_length)
2557 << " -> " << static_cast<int>(server_connection_id_length);
2558 *expected_server_connection_id_length = server_connection_id_length;
2559 }
2560 }
dschinazi8ff74822019-05-28 16:37:20 -07002561 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002562 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002563 scil != *source_connection_id_length) &&
dschinazi97da52b2020-01-13 15:44:43 -08002564 version.IsKnown() && !version.AllowsVariableLengthConnectionIds()) {
fayang40315542019-05-09 09:19:09 -07002565 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2566 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002567 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002568 return false;
2569 }
2570 *destination_connection_id_length = dcil;
2571 *source_connection_id_length = scil;
2572 return true;
2573}
2574
dschinazib953d022019-08-01 18:05:58 -07002575bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2576 if (!QuicUtils::IsConnectionIdValidForVersion(
2577 GetServerConnectionIdAsRecipient(header, perspective_),
2578 transport_version())) {
2579 set_detailed_error("Received server connection ID with invalid length.");
2580 return false;
2581 }
2582
2583 if (version_.SupportsClientConnectionIds() &&
2584 !QuicUtils::IsConnectionIdValidForVersion(
2585 GetClientConnectionIdAsRecipient(header, perspective_),
2586 transport_version())) {
2587 set_detailed_error("Received client connection ID with invalid length.");
2588 return false;
2589 }
2590 return true;
2591}
2592
QUICHE teama6ef0a62019-03-07 20:34:33 -05002593bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2594 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002595 if (version_.HasLengthPrefixedConnectionIds()) {
2596 uint8_t expected_destination_connection_id_length =
2597 perspective_ == Perspective::IS_CLIENT
2598 ? expected_client_connection_id_length_
2599 : expected_server_connection_id_length_;
2600 QuicVersionLabel version_label;
2601 bool has_length_prefix;
2602 std::string detailed_error;
2603 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2604 reader, expected_destination_connection_id_length,
2605 VersionHasIetfInvariantHeader(version_.transport_version),
2606 &header->type_byte, &header->form, &header->version_flag,
2607 &has_length_prefix, &version_label, &header->version,
2608 &header->destination_connection_id, &header->source_connection_id,
2609 &header->long_packet_type, &header->retry_token_length_length,
2610 &header->retry_token, &detailed_error);
2611 if (parse_result != QUIC_NO_ERROR) {
2612 set_detailed_error(detailed_error);
2613 return false;
2614 }
2615 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2616 header->source_connection_id_included =
2617 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2618 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2619 DCHECK(header->source_connection_id.IsEmpty());
2620 if (perspective_ == Perspective::IS_CLIENT) {
2621 header->source_connection_id = last_serialized_server_connection_id_;
2622 } else {
2623 header->source_connection_id = last_serialized_client_connection_id_;
2624 }
2625 }
dschinazib953d022019-08-01 18:05:58 -07002626
2627 if (!ValidateReceivedConnectionIds(*header)) {
2628 return false;
2629 }
2630
dschinazi48ac9192019-07-31 00:07:26 -07002631 if (header->version_flag &&
fayang36825da2019-08-21 14:01:27 -07002632 header->long_packet_type != VERSION_NEGOTIATION &&
dschinazi48ac9192019-07-31 00:07:26 -07002633 !(header->type_byte & FLAGS_FIXED_BIT)) {
2634 set_detailed_error("Fixed bit is 0 in long header.");
2635 return false;
2636 }
fayang36825da2019-08-21 14:01:27 -07002637 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
dschinazi48ac9192019-07-31 00:07:26 -07002638 set_detailed_error("Fixed bit is 0 in short header.");
2639 return false;
2640 }
2641 if (!header->version_flag) {
fayang36825da2019-08-21 14:01:27 -07002642 if (!version_.HasHeaderProtection()) {
2643 header->packet_number_length =
2644 GetShortHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002645 }
2646 return true;
2647 }
2648 if (header->long_packet_type == RETRY) {
2649 if (!version().SupportsRetry()) {
2650 set_detailed_error("RETRY not supported in this version.");
2651 return false;
2652 }
2653 if (perspective_ == Perspective::IS_SERVER) {
2654 set_detailed_error("Client-initiated RETRY is invalid.");
2655 return false;
2656 }
2657 return true;
2658 }
dschinazi97da52b2020-01-13 15:44:43 -08002659 if (header->version.IsKnown() && !header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002660 header->packet_number_length =
2661 GetLongHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002662 }
2663
2664 return true;
2665 }
2666
QUICHE teama6ef0a62019-03-07 20:34:33 -05002667 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2668 return false;
2669 }
2670
2671 uint8_t destination_connection_id_length =
2672 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002673 ? (perspective_ == Perspective::IS_SERVER
2674 ? expected_server_connection_id_length_
2675 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002676 : 0;
2677 uint8_t source_connection_id_length =
2678 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002679 ? (perspective_ == Perspective::IS_CLIENT
2680 ? expected_server_connection_id_length_
2681 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002682 : 0;
2683 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002684 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002685 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002686 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002687 &expected_server_connection_id_length_,
2688 &destination_connection_id_length, &source_connection_id_length,
2689 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002690 return false;
2691 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002692 }
2693
2694 // Read connection ID.
2695 if (!reader->ReadConnectionId(&header->destination_connection_id,
2696 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002697 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002698 return false;
2699 }
2700
2701 if (!reader->ReadConnectionId(&header->source_connection_id,
2702 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002703 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002704 return false;
2705 }
2706
dschinazi5e1a7b22019-07-31 12:23:21 -07002707 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2708 if (!header->source_connection_id.IsEmpty()) {
2709 DCHECK(!version_.SupportsClientConnectionIds());
2710 set_detailed_error("Client connection ID not supported in this version.");
2711 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002712 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002713 if (perspective_ == Perspective::IS_CLIENT) {
2714 header->source_connection_id = last_serialized_server_connection_id_;
2715 } else {
2716 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002717 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002718 }
2719
dschinazib953d022019-08-01 18:05:58 -07002720 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002721}
2722
2723bool QuicFramer::ProcessAndCalculatePacketNumber(
2724 QuicDataReader* reader,
2725 QuicPacketNumberLength packet_number_length,
2726 QuicPacketNumber base_packet_number,
2727 uint64_t* packet_number) {
2728 uint64_t wire_packet_number;
2729 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2730 return false;
2731 }
2732
2733 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2734 // in case the first guess is incorrect.
2735 *packet_number = CalculatePacketNumberFromWire(
2736 packet_number_length, base_packet_number, wire_packet_number);
2737 return true;
2738}
2739
2740bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2741 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002742 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2743 << "IETF QUIC Framing negotiated but attempting to process frames as "
2744 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002745 if (reader->IsDoneReading()) {
2746 set_detailed_error("Packet has no frames.");
2747 return RaiseError(QUIC_MISSING_PAYLOAD);
2748 }
dschinazi118934b2019-06-13 18:09:08 -07002749 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002750 while (!reader->IsDoneReading()) {
2751 uint8_t frame_type;
2752 if (!reader->ReadBytes(&frame_type, 1)) {
2753 set_detailed_error("Unable to read frame type.");
2754 return RaiseError(QUIC_INVALID_FRAME_DATA);
2755 }
fayang36825da2019-08-21 14:01:27 -07002756 const uint8_t special_mask = transport_version() <= QUIC_VERSION_43
QUICHE teama6ef0a62019-03-07 20:34:33 -05002757 ? kQuicFrameTypeBrokenMask
2758 : kQuicFrameTypeSpecialMask;
2759 if (frame_type & special_mask) {
2760 // Stream Frame
2761 if (frame_type & kQuicFrameTypeStreamMask) {
2762 QuicStreamFrame frame;
2763 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2764 return RaiseError(QUIC_INVALID_STREAM_DATA);
2765 }
dschinazi118934b2019-06-13 18:09:08 -07002766 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002767 if (!visitor_->OnStreamFrame(frame)) {
2768 QUIC_DVLOG(1) << ENDPOINT
2769 << "Visitor asked to stop further processing.";
2770 // Returning true since there was no parsing error.
2771 return true;
2772 }
2773 continue;
2774 }
2775
2776 // Ack Frame
2777 if (frame_type & kQuicFrameTypeAckMask) {
2778 if (!ProcessAckFrame(reader, frame_type)) {
2779 return RaiseError(QUIC_INVALID_ACK_DATA);
2780 }
dschinazi118934b2019-06-13 18:09:08 -07002781 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002782 continue;
2783 }
2784
2785 // This was a special frame type that did not match any
2786 // of the known ones. Error.
2787 set_detailed_error("Illegal frame type.");
2788 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2789 << static_cast<int>(frame_type);
2790 return RaiseError(QUIC_INVALID_FRAME_DATA);
2791 }
2792
2793 switch (frame_type) {
2794 case PADDING_FRAME: {
2795 QuicPaddingFrame frame;
2796 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002797 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002798 if (!visitor_->OnPaddingFrame(frame)) {
2799 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2800 // Returning true since there was no parsing error.
2801 return true;
2802 }
2803 continue;
2804 }
2805
2806 case RST_STREAM_FRAME: {
2807 QuicRstStreamFrame frame;
2808 if (!ProcessRstStreamFrame(reader, &frame)) {
2809 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2810 }
dschinazi118934b2019-06-13 18:09:08 -07002811 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002812 if (!visitor_->OnRstStreamFrame(frame)) {
2813 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2814 // Returning true since there was no parsing error.
2815 return true;
2816 }
2817 continue;
2818 }
2819
2820 case CONNECTION_CLOSE_FRAME: {
2821 QuicConnectionCloseFrame frame;
2822 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2823 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2824 }
2825
dschinazi118934b2019-06-13 18:09:08 -07002826 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2827 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002828 if (!visitor_->OnConnectionCloseFrame(frame)) {
2829 QUIC_DVLOG(1) << ENDPOINT
2830 << "Visitor asked to stop further processing.";
2831 // Returning true since there was no parsing error.
2832 return true;
2833 }
2834 continue;
2835 }
2836
2837 case GOAWAY_FRAME: {
2838 QuicGoAwayFrame goaway_frame;
2839 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2840 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2841 }
dschinazi118934b2019-06-13 18:09:08 -07002842 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2843 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002844 if (!visitor_->OnGoAwayFrame(goaway_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 WINDOW_UPDATE_FRAME: {
2854 QuicWindowUpdateFrame window_update_frame;
2855 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2856 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2857 }
dschinazi118934b2019-06-13 18:09:08 -07002858 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2859 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002860 if (!visitor_->OnWindowUpdateFrame(window_update_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 BLOCKED_FRAME: {
2870 QuicBlockedFrame blocked_frame;
2871 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2872 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2873 }
dschinazi118934b2019-06-13 18:09:08 -07002874 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2875 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002876 if (!visitor_->OnBlockedFrame(blocked_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 STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002886 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayang36825da2019-08-21 14:01:27 -07002887 version_.transport_version > QUIC_VERSION_43) {
ianswett97b690b2019-05-02 15:12:43 -07002888 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2889 set_detailed_error("STOP WAITING not supported in version 44+.");
2890 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2891 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002892 QuicStopWaitingFrame stop_waiting_frame;
2893 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2894 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2895 }
dschinazi118934b2019-06-13 18:09:08 -07002896 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2897 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002898 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2899 QUIC_DVLOG(1) << ENDPOINT
2900 << "Visitor asked to stop further processing.";
2901 // Returning true since there was no parsing error.
2902 return true;
2903 }
2904 continue;
2905 }
2906 case PING_FRAME: {
2907 // Ping has no payload.
2908 QuicPingFrame ping_frame;
2909 if (!visitor_->OnPingFrame(ping_frame)) {
2910 QUIC_DVLOG(1) << ENDPOINT
2911 << "Visitor asked to stop further processing.";
2912 // Returning true since there was no parsing error.
2913 return true;
2914 }
dschinazi118934b2019-06-13 18:09:08 -07002915 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002916 continue;
2917 }
2918 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2919 QUIC_FALLTHROUGH_INTENDED;
2920 case IETF_EXTENSION_MESSAGE: {
2921 QuicMessageFrame message_frame;
2922 if (!ProcessMessageFrame(reader,
2923 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2924 &message_frame)) {
2925 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2926 }
dschinazi118934b2019-06-13 18:09:08 -07002927 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
2928 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002929 if (!visitor_->OnMessageFrame(message_frame)) {
2930 QUIC_DVLOG(1) << ENDPOINT
2931 << "Visitor asked to stop further processing.";
2932 // Returning true since there was no parsing error.
2933 return true;
2934 }
2935 break;
2936 }
2937 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07002938 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002939 set_detailed_error("Illegal frame type.");
2940 return RaiseError(QUIC_INVALID_FRAME_DATA);
2941 }
2942 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08002943 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002944 return RaiseError(QUIC_INVALID_FRAME_DATA);
2945 }
dschinazi118934b2019-06-13 18:09:08 -07002946 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002947 if (!visitor_->OnCryptoFrame(frame)) {
2948 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2949 // Returning true since there was no parsing error.
2950 return true;
2951 }
2952 break;
2953 }
2954
2955 default:
2956 set_detailed_error("Illegal frame type.");
2957 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2958 << static_cast<int>(frame_type);
2959 return RaiseError(QUIC_INVALID_FRAME_DATA);
2960 }
2961 }
2962
2963 return true;
2964}
2965
2966bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
2967 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002968 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
2969 << "Attempt to process frames as IETF frames but version ("
2970 << version_.transport_version << ") does not support IETF Framing.";
2971
QUICHE teama6ef0a62019-03-07 20:34:33 -05002972 if (reader->IsDoneReading()) {
2973 set_detailed_error("Packet has no frames.");
2974 return RaiseError(QUIC_MISSING_PAYLOAD);
2975 }
dschinazi118934b2019-06-13 18:09:08 -07002976
2977 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002978 while (!reader->IsDoneReading()) {
2979 uint64_t frame_type;
2980 // Will be the number of bytes into which frame_type was encoded.
2981 size_t encoded_bytes = reader->BytesRemaining();
2982 if (!reader->ReadVarInt62(&frame_type)) {
2983 set_detailed_error("Unable to read frame type.");
2984 return RaiseError(QUIC_INVALID_FRAME_DATA);
2985 }
fkastenholza3660102019-08-28 05:19:24 -07002986 current_received_frame_type_ = frame_type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002987
2988 // Is now the number of bytes into which the frame type was encoded.
2989 encoded_bytes -= reader->BytesRemaining();
2990
2991 // Check that the frame type is minimally encoded.
2992 if (encoded_bytes !=
2993 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
2994 // The frame type was not minimally encoded.
2995 set_detailed_error("Frame type not minimally encoded.");
2996 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
2997 }
2998
2999 if (IS_IETF_STREAM_FRAME(frame_type)) {
3000 QuicStreamFrame frame;
3001 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3002 return RaiseError(QUIC_INVALID_STREAM_DATA);
3003 }
dschinazi118934b2019-06-13 18:09:08 -07003004 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003005 if (!visitor_->OnStreamFrame(frame)) {
3006 QUIC_DVLOG(1) << ENDPOINT
3007 << "Visitor asked to stop further processing.";
3008 // Returning true since there was no parsing error.
3009 return true;
3010 }
3011 } else {
3012 switch (frame_type) {
3013 case IETF_PADDING: {
3014 QuicPaddingFrame frame;
3015 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003016 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3017 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003018 if (!visitor_->OnPaddingFrame(frame)) {
3019 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3020 // Returning true since there was no parsing error.
3021 return true;
3022 }
3023 break;
3024 }
3025 case IETF_RST_STREAM: {
3026 QuicRstStreamFrame frame;
3027 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3028 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3029 }
dschinazi118934b2019-06-13 18:09:08 -07003030 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3031 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003032 if (!visitor_->OnRstStreamFrame(frame)) {
3033 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3034 // Returning true since there was no parsing error.
3035 return true;
3036 }
3037 break;
3038 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003039 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003040 case IETF_CONNECTION_CLOSE: {
3041 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003042 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003043 reader,
3044 (frame_type == IETF_CONNECTION_CLOSE)
3045 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3046 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3047 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003048 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3049 }
dschinazi118934b2019-06-13 18:09:08 -07003050 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3051 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003052 if (!visitor_->OnConnectionCloseFrame(frame)) {
3053 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3054 // Returning true since there was no parsing error.
3055 return true;
3056 }
3057 break;
3058 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003059 case IETF_MAX_DATA: {
3060 QuicWindowUpdateFrame frame;
3061 if (!ProcessMaxDataFrame(reader, &frame)) {
3062 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3063 }
dschinazi118934b2019-06-13 18:09:08 -07003064 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3065 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003066 if (!visitor_->OnWindowUpdateFrame(frame)) {
3067 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3068 // Returning true since there was no parsing error.
3069 return true;
3070 }
3071 break;
3072 }
3073 case IETF_MAX_STREAM_DATA: {
3074 QuicWindowUpdateFrame frame;
3075 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3076 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3077 }
dschinazi118934b2019-06-13 18:09:08 -07003078 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3079 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003080 if (!visitor_->OnWindowUpdateFrame(frame)) {
3081 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3082 // Returning true since there was no parsing error.
3083 return true;
3084 }
3085 break;
3086 }
3087 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3088 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003089 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003090 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003091 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003092 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003093 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003094 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3095 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003096 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003097 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_PING: {
3104 // Ping has no payload.
3105 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003106 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3107 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003108 if (!visitor_->OnPingFrame(ping_frame)) {
3109 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3110 // Returning true since there was no parsing error.
3111 return true;
3112 }
3113 break;
3114 }
ianswett2f077442019-12-12 11:51:24 -08003115 case IETF_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003116 QuicBlockedFrame frame;
3117 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3118 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3119 }
dschinazi118934b2019-06-13 18:09:08 -07003120 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3121 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003122 if (!visitor_->OnBlockedFrame(frame)) {
3123 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3124 // Returning true since there was no parsing error.
3125 return true;
3126 }
3127 break;
3128 }
ianswett2f077442019-12-12 11:51:24 -08003129 case IETF_STREAM_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130 QuicBlockedFrame frame;
3131 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3132 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3133 }
dschinazi118934b2019-06-13 18:09:08 -07003134 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3135 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003136 if (!visitor_->OnBlockedFrame(frame)) {
3137 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3138 // Returning true since there was no parsing error.
3139 return true;
3140 }
3141 break;
3142 }
3143 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3144 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003145 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003146 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003147 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003148 }
dschinazi118934b2019-06-13 18:09:08 -07003149 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3150 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003151 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003152 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3153 // Returning true since there was no parsing error.
3154 return true;
3155 }
3156 break;
3157 }
3158 case IETF_NEW_CONNECTION_ID: {
3159 QuicNewConnectionIdFrame frame;
3160 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3161 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3162 }
dschinazi118934b2019-06-13 18:09:08 -07003163 QUIC_DVLOG(2) << ENDPOINT
3164 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003165 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3166 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3167 // Returning true since there was no parsing error.
3168 return true;
3169 }
3170 break;
3171 }
3172 case IETF_RETIRE_CONNECTION_ID: {
3173 QuicRetireConnectionIdFrame frame;
3174 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3175 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3176 }
dschinazi118934b2019-06-13 18:09:08 -07003177 QUIC_DVLOG(2) << ENDPOINT
3178 << "Processing IETF retire connection ID frame "
3179 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003180 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3181 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3182 // Returning true since there was no parsing error.
3183 return true;
3184 }
3185 break;
3186 }
3187 case IETF_NEW_TOKEN: {
3188 QuicNewTokenFrame frame;
3189 if (!ProcessNewTokenFrame(reader, &frame)) {
3190 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3191 }
dschinazi118934b2019-06-13 18:09:08 -07003192 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3193 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003194 if (!visitor_->OnNewTokenFrame(frame)) {
3195 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3196 // Returning true since there was no parsing error.
3197 return true;
3198 }
3199 break;
3200 }
3201 case IETF_STOP_SENDING: {
3202 QuicStopSendingFrame frame;
3203 if (!ProcessStopSendingFrame(reader, &frame)) {
3204 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3205 }
dschinazi118934b2019-06-13 18:09:08 -07003206 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3207 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003208 if (!visitor_->OnStopSendingFrame(frame)) {
3209 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3210 // Returning true since there was no parsing error.
3211 return true;
3212 }
3213 break;
3214 }
3215 case IETF_ACK_ECN:
3216 case IETF_ACK: {
3217 QuicAckFrame frame;
3218 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3219 return RaiseError(QUIC_INVALID_ACK_DATA);
3220 }
dschinazi118934b2019-06-13 18:09:08 -07003221 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003222 break;
3223 }
3224 case IETF_PATH_CHALLENGE: {
3225 QuicPathChallengeFrame frame;
3226 if (!ProcessPathChallengeFrame(reader, &frame)) {
3227 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3228 }
dschinazi118934b2019-06-13 18:09:08 -07003229 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3230 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003231 if (!visitor_->OnPathChallengeFrame(frame)) {
3232 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3233 // Returning true since there was no parsing error.
3234 return true;
3235 }
3236 break;
3237 }
3238 case IETF_PATH_RESPONSE: {
3239 QuicPathResponseFrame frame;
3240 if (!ProcessPathResponseFrame(reader, &frame)) {
3241 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3242 }
dschinazi118934b2019-06-13 18:09:08 -07003243 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3244 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003245 if (!visitor_->OnPathResponseFrame(frame)) {
3246 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3247 // Returning true since there was no parsing error.
3248 return true;
3249 }
3250 break;
3251 }
dschinazicd86dd12019-11-14 10:11:13 -08003252 case IETF_EXTENSION_MESSAGE_NO_LENGTH_V99:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003253 QUIC_FALLTHROUGH_INTENDED;
dschinazicd86dd12019-11-14 10:11:13 -08003254 case IETF_EXTENSION_MESSAGE_V99: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003255 QuicMessageFrame message_frame;
3256 if (!ProcessMessageFrame(
dschinazicd86dd12019-11-14 10:11:13 -08003257 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH_V99,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003258 &message_frame)) {
3259 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3260 }
dschinazi118934b2019-06-13 18:09:08 -07003261 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3262 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003263 if (!visitor_->OnMessageFrame(message_frame)) {
3264 QUIC_DVLOG(1) << ENDPOINT
3265 << "Visitor asked to stop further processing.";
3266 // Returning true since there was no parsing error.
3267 return true;
3268 }
3269 break;
3270 }
3271 case IETF_CRYPTO: {
3272 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08003273 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003274 return RaiseError(QUIC_INVALID_FRAME_DATA);
3275 }
dschinazi118934b2019-06-13 18:09:08 -07003276 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003277 if (!visitor_->OnCryptoFrame(frame)) {
3278 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3279 // Returning true since there was no parsing error.
3280 return true;
3281 }
3282 break;
3283 }
fayang01062942020-01-22 07:23:23 -08003284 case IETF_HANDSHAKE_DONE: {
3285 // HANDSHAKE_DONE has no payload.
3286 QuicHandshakeDoneFrame handshake_done_frame;
3287 if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) {
3288 QUIC_DVLOG(1) << ENDPOINT
3289 << "Visitor asked to stop further processing.";
3290 // Returning true since there was no parsing error.
3291 return true;
3292 }
3293 QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame "
3294 << handshake_done_frame;
3295 break;
3296 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003297
3298 default:
3299 set_detailed_error("Illegal frame type.");
3300 QUIC_DLOG(WARNING)
3301 << ENDPOINT
3302 << "Illegal frame type: " << static_cast<int>(frame_type);
3303 return RaiseError(QUIC_INVALID_FRAME_DATA);
3304 }
3305 }
3306 }
3307 return true;
3308}
3309
3310namespace {
3311// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3312inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3313 return (1u << num_bits) - 1;
3314}
3315
3316// Extract |num_bits| from |flags| offset by |offset|.
3317uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3318 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3319}
3320
3321// Extract the bit at position |offset| from |flags| as a bool.
3322bool ExtractBit(uint8_t flags, uint8_t offset) {
3323 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3324}
3325
3326// Set |num_bits|, offset by |offset| to |val| in |flags|.
3327void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3328 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3329 *flags |= val << offset;
3330}
3331
3332// Set the bit at position |offset| to |val| in |flags|.
3333void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3334 SetBits(flags, val ? 1 : 0, 1, offset);
3335}
3336} // namespace
3337
3338bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3339 uint8_t frame_type,
3340 QuicStreamFrame* frame) {
3341 uint8_t stream_flags = frame_type;
3342
3343 uint8_t stream_id_length = 0;
3344 uint8_t offset_length = 4;
3345 bool has_data_length = true;
3346 stream_flags &= ~kQuicFrameTypeStreamMask;
3347
3348 // Read from right to left: StreamID, Offset, Data Length, Fin.
3349 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3350 stream_flags >>= kQuicStreamIdShift;
3351
3352 offset_length = (stream_flags & kQuicStreamOffsetMask);
3353 // There is no encoding for 1 byte, only 0 and 2 through 8.
3354 if (offset_length > 0) {
3355 offset_length += 1;
3356 }
3357 stream_flags >>= kQuicStreamShift;
3358
3359 has_data_length =
3360 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3361 stream_flags >>= kQuicStreamDataLengthShift;
3362
3363 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3364
3365 uint64_t stream_id;
3366 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3367 set_detailed_error("Unable to read stream_id.");
3368 return false;
3369 }
3370 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3371
3372 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3373 set_detailed_error("Unable to read offset.");
3374 return false;
3375 }
3376
dmcardlecf0bfcf2019-12-13 08:08:21 -08003377 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3378 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003379 if (has_data_length) {
3380 if (!reader->ReadStringPiece16(&data)) {
3381 set_detailed_error("Unable to read frame data.");
3382 return false;
3383 }
3384 } else {
3385 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3386 set_detailed_error("Unable to read frame data.");
3387 return false;
3388 }
3389 }
3390 frame->data_buffer = data.data();
3391 frame->data_length = static_cast<uint16_t>(data.length());
3392
3393 return true;
3394}
3395
3396bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3397 uint8_t frame_type,
3398 QuicStreamFrame* frame) {
3399 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003400 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003401 set_detailed_error("Unable to read stream_id.");
3402 return false;
3403 }
3404
3405 // If we have a data offset, read it. If not, set to 0.
3406 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3407 if (!reader->ReadVarInt62(&frame->offset)) {
3408 set_detailed_error("Unable to read stream data offset.");
3409 return false;
3410 }
3411 } else {
3412 // no offset in the frame, ensure it's 0 in the Frame.
3413 frame->offset = 0;
3414 }
3415
3416 // If we have a data length, read it. If not, set to 0.
3417 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3418 QuicIetfStreamDataLength length;
3419 if (!reader->ReadVarInt62(&length)) {
3420 set_detailed_error("Unable to read stream data length.");
3421 return false;
3422 }
3423 if (length > 0xffff) {
3424 set_detailed_error("Stream data length is too large.");
3425 return false;
3426 }
3427 frame->data_length = length;
3428 } else {
3429 // no length in the frame, it is the number of bytes remaining in the
3430 // packet.
3431 frame->data_length = reader->BytesRemaining();
3432 }
3433
3434 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3435 frame->fin = true;
3436 } else {
3437 frame->fin = false;
3438 }
3439
dmcardlecf0bfcf2019-12-13 08:08:21 -08003440 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3441 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003442 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3443 set_detailed_error("Unable to read frame data.");
3444 return false;
3445 }
3446 frame->data_buffer = data.data();
3447 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3448
3449 return true;
3450}
3451
3452bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
renjietang15dfaa82020-01-03 16:13:38 -08003453 EncryptionLevel encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003454 QuicCryptoFrame* frame) {
renjietang15dfaa82020-01-03 16:13:38 -08003455 frame->level = encryption_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003456 if (!reader->ReadVarInt62(&frame->offset)) {
3457 set_detailed_error("Unable to read crypto data offset.");
3458 return false;
3459 }
3460 uint64_t len;
3461 if (!reader->ReadVarInt62(&len) ||
3462 len > std::numeric_limits<QuicPacketLength>::max()) {
3463 set_detailed_error("Invalid data length.");
3464 return false;
3465 }
3466 frame->data_length = len;
3467
dmcardlecf0bfcf2019-12-13 08:08:21 -08003468 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3469 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003470 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3471 set_detailed_error("Unable to read frame data.");
3472 return false;
3473 }
3474 frame->data_buffer = data.data();
3475 return true;
3476}
3477
3478bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3479 const bool has_ack_blocks =
3480 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3481 uint8_t num_ack_blocks = 0;
3482 uint8_t num_received_packets = 0;
3483
3484 // Determine the two lengths from the frame type: largest acked length,
3485 // ack block length.
3486 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003487 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3488 kActBlockLengthOffset));
3489 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003490 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3491 kLargestAckedOffset));
3492
3493 uint64_t largest_acked;
3494 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3495 set_detailed_error("Unable to read largest acked.");
3496 return false;
3497 }
3498
3499 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3500 // Connection always sends packet starting from kFirstSendingPacketNumber >
3501 // 0, peer has observed an unsent packet.
3502 set_detailed_error("Largest acked is 0.");
3503 return false;
3504 }
3505
3506 uint64_t ack_delay_time_us;
3507 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3508 set_detailed_error("Unable to read ack delay time.");
3509 return false;
3510 }
3511
3512 if (!visitor_->OnAckFrameStart(
3513 QuicPacketNumber(largest_acked),
3514 ack_delay_time_us == kUFloat16MaxValue
3515 ? QuicTime::Delta::Infinite()
3516 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3517 // The visitor suppresses further processing of the packet. Although this is
3518 // not a parsing error, returns false as this is in middle of processing an
3519 // ack frame,
3520 set_detailed_error("Visitor suppresses further processing of ack frame.");
3521 return false;
3522 }
3523
3524 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3525 set_detailed_error("Unable to read num of ack blocks.");
3526 return false;
3527 }
3528
3529 uint64_t first_block_length;
3530 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3531 set_detailed_error("Unable to read first ack block length.");
3532 return false;
3533 }
3534
3535 if (first_block_length == 0) {
3536 set_detailed_error("First block length is zero.");
3537 return false;
3538 }
3539 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3540 if (first_block_length + first_sending_packet_number_.ToUint64() >
3541 largest_acked + 1) {
3542 first_ack_block_underflow = true;
3543 }
3544 if (first_ack_block_underflow) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003545 set_detailed_error(
3546 quiche::QuicheStrCat("Underflow with first ack block length ",
3547 first_block_length, " largest acked is ",
3548 largest_acked, ".")
3549 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003550 return false;
3551 }
3552
3553 uint64_t first_received = largest_acked + 1 - first_block_length;
3554 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3555 QuicPacketNumber(largest_acked + 1))) {
3556 // The visitor suppresses further processing of the packet. Although
3557 // this is not a parsing error, returns false as this is in middle
3558 // of processing an ack frame,
3559 set_detailed_error("Visitor suppresses further processing of ack frame.");
3560 return false;
3561 }
3562
3563 if (num_ack_blocks > 0) {
3564 for (size_t i = 0; i < num_ack_blocks; ++i) {
3565 uint8_t gap = 0;
3566 if (!reader->ReadUInt8(&gap)) {
3567 set_detailed_error("Unable to read gap to next ack block.");
3568 return false;
3569 }
3570 uint64_t current_block_length;
3571 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3572 set_detailed_error("Unable to ack block length.");
3573 return false;
3574 }
3575 bool ack_block_underflow = first_received < gap + current_block_length;
3576 if (first_received < gap + current_block_length +
3577 first_sending_packet_number_.ToUint64()) {
3578 ack_block_underflow = true;
3579 }
3580 if (ack_block_underflow) {
3581 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003582 quiche::QuicheStrCat("Underflow with ack block length ",
3583 current_block_length, ", end of block is ",
3584 first_received - gap, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003585 .c_str());
3586 return false;
3587 }
3588
3589 first_received -= (gap + current_block_length);
3590 if (current_block_length > 0) {
3591 if (!visitor_->OnAckRange(
3592 QuicPacketNumber(first_received),
3593 QuicPacketNumber(first_received) + current_block_length)) {
3594 // The visitor suppresses further processing of the packet. Although
3595 // this is not a parsing error, returns false as this is in middle
3596 // of processing an ack frame,
3597 set_detailed_error(
3598 "Visitor suppresses further processing of ack frame.");
3599 return false;
3600 }
3601 }
3602 }
3603 }
3604
3605 if (!reader->ReadUInt8(&num_received_packets)) {
3606 set_detailed_error("Unable to read num received packets.");
3607 return false;
3608 }
3609
3610 if (!ProcessTimestampsInAckFrame(num_received_packets,
3611 QuicPacketNumber(largest_acked), reader)) {
3612 return false;
3613 }
3614
3615 // Done processing the ACK frame.
fayang533cb1b2020-01-28 08:05:08 -08003616 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(first_received))) {
3617 set_detailed_error(
3618 "Error occurs when visitor finishes processing the ACK frame.");
3619 return false;
3620 }
3621
3622 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003623}
3624
3625bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3626 QuicPacketNumber largest_acked,
3627 QuicDataReader* reader) {
3628 if (num_received_packets == 0) {
3629 return true;
3630 }
3631 uint8_t delta_from_largest_observed;
3632 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3633 set_detailed_error("Unable to read sequence delta in received packets.");
3634 return false;
3635 }
3636
3637 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003638 set_detailed_error(
3639 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3640 delta_from_largest_observed,
3641 ", largest_acked: ", largest_acked.ToUint64())
3642 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003643 return false;
3644 }
3645
3646 // Time delta from the framer creation.
3647 uint32_t time_delta_us;
3648 if (!reader->ReadUInt32(&time_delta_us)) {
3649 set_detailed_error("Unable to read time delta in received packets.");
3650 return false;
3651 }
3652
3653 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3654 if (process_timestamps_) {
3655 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3656
3657 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3658 }
3659
3660 for (uint8_t i = 1; i < num_received_packets; ++i) {
3661 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3662 set_detailed_error("Unable to read sequence delta in received packets.");
3663 return false;
3664 }
3665 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3666 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003667 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3668 delta_from_largest_observed,
3669 ", largest_acked: ", largest_acked.ToUint64())
QUICHE teama6ef0a62019-03-07 20:34:33 -05003670 .c_str());
3671 return false;
3672 }
3673 seq_num = largest_acked - delta_from_largest_observed;
3674
3675 // Time delta from the previous timestamp.
3676 uint64_t incremental_time_delta_us;
3677 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3678 set_detailed_error(
3679 "Unable to read incremental time delta in received packets.");
3680 return false;
3681 }
3682
3683 if (process_timestamps_) {
3684 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3685 incremental_time_delta_us);
3686 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3687 }
3688 }
3689 return true;
3690}
3691
3692bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3693 uint64_t frame_type,
3694 QuicAckFrame* ack_frame) {
3695 uint64_t largest_acked;
3696 if (!reader->ReadVarInt62(&largest_acked)) {
3697 set_detailed_error("Unable to read largest acked.");
3698 return false;
3699 }
3700 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3701 // Connection always sends packet starting from kFirstSendingPacketNumber >
3702 // 0, peer has observed an unsent packet.
3703 set_detailed_error("Largest acked is 0.");
3704 return false;
3705 }
3706 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3707 uint64_t ack_delay_time_in_us;
3708 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3709 set_detailed_error("Unable to read ack delay time.");
3710 return false;
3711 }
3712
fayang3371b092019-12-04 07:08:52 -08003713 if (ack_delay_time_in_us >= (kVarInt62MaxValue >> peer_ack_delay_exponent_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003714 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3715 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003716 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003717 ack_frame->ack_delay_time =
3718 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3719 }
3720 if (frame_type == IETF_ACK_ECN) {
3721 ack_frame->ecn_counters_populated = true;
3722 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3723 set_detailed_error("Unable to read ack ect_0_count.");
3724 return false;
3725 }
3726 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3727 set_detailed_error("Unable to read ack ect_1_count.");
3728 return false;
3729 }
3730 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3731 set_detailed_error("Unable to read ack ecn_ce_count.");
3732 return false;
3733 }
3734 } else {
3735 ack_frame->ecn_counters_populated = false;
3736 ack_frame->ect_0_count = 0;
3737 ack_frame->ect_1_count = 0;
3738 ack_frame->ecn_ce_count = 0;
3739 }
3740 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3741 ack_frame->ack_delay_time)) {
3742 // The visitor suppresses further processing of the packet. Although this is
3743 // not a parsing error, returns false as this is in middle of processing an
3744 // ACK frame.
3745 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3746 return false;
3747 }
3748
3749 // Get number of ACK blocks from the packet.
3750 uint64_t ack_block_count;
3751 if (!reader->ReadVarInt62(&ack_block_count)) {
3752 set_detailed_error("Unable to read ack block count.");
3753 return false;
3754 }
3755 // There always is a first ACK block, which is the (number of packets being
3756 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3757 // value is 0, then only largest is acked. If it is 1, then largest-1,
3758 // largest] are acked, etc
3759 uint64_t ack_block_value;
3760 if (!reader->ReadVarInt62(&ack_block_value)) {
3761 set_detailed_error("Unable to read first ack block length.");
3762 return false;
3763 }
3764 // Calculate the packets being acked in the first block.
3765 // +1 because AddRange implementation requires [low,high)
3766 uint64_t block_high = largest_acked + 1;
3767 uint64_t block_low = largest_acked - ack_block_value;
3768
3769 // ack_block_value is the number of packets preceding the
3770 // largest_acked packet which are in the block being acked. Thus,
3771 // its maximum value is largest_acked-1. Test this, reporting an
3772 // error if the value is wrong.
3773 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3774 largest_acked) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003775 set_detailed_error(
3776 quiche::QuicheStrCat("Underflow with first ack block length ",
3777 ack_block_value + 1, " largest acked is ",
3778 largest_acked, ".")
3779 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003780 return false;
3781 }
3782
3783 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3784 QuicPacketNumber(block_high))) {
3785 // The visitor suppresses further processing of the packet. Although
3786 // this is not a parsing error, returns false as this is in middle
3787 // of processing an ACK frame.
3788 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3789 return false;
3790 }
3791
3792 while (ack_block_count != 0) {
3793 uint64_t gap_block_value;
3794 // Get the sizes of the gap and ack blocks,
3795 if (!reader->ReadVarInt62(&gap_block_value)) {
3796 set_detailed_error("Unable to read gap block value.");
3797 return false;
3798 }
3799 // It's an error if the gap is larger than the space from packet
3800 // number 0 to the start of the block that's just been acked, PLUS
3801 // there must be space for at least 1 packet to be acked. For
3802 // example, if block_low is 10 and gap_block_value is 9, it means
3803 // the gap block is 10 packets long, leaving no room for a packet
3804 // to be acked. Thus, gap_block_value+2 can not be larger than
3805 // block_low.
3806 // The test is written this way to detect wrap-arounds.
3807 if ((gap_block_value + 2) > block_low) {
3808 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003809 quiche::QuicheStrCat("Underflow with gap block length ",
3810 gap_block_value + 1,
3811 " previous ack block start is ", block_low, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003812 .c_str());
3813 return false;
3814 }
3815
3816 // Adjust block_high to be the top of the next ack block.
3817 // There is a gap of |gap_block_value| packets between the bottom
3818 // of ack block N and top of block N+1. Note that gap_block_value
3819 // is he size of the gap minus 1 (per the QUIC protocol), and
3820 // block_high is the packet number of the first packet of the gap
3821 // (per the implementation of OnAckRange/AddAckRange, below).
3822 block_high = block_low - 1 - gap_block_value;
3823
3824 if (!reader->ReadVarInt62(&ack_block_value)) {
3825 set_detailed_error("Unable to read ack block value.");
3826 return false;
3827 }
3828 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3829 (block_high - 1)) {
3830 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003831 quiche::QuicheStrCat("Underflow with ack block length ",
3832 ack_block_value + 1, " latest ack block end is ",
3833 block_high - 1, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003834 .c_str());
3835 return false;
3836 }
3837 // Calculate the low end of the new nth ack block. The +1 is
3838 // because the encoded value is the blocksize-1.
3839 block_low = block_high - 1 - ack_block_value;
3840 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3841 QuicPacketNumber(block_high))) {
3842 // The visitor suppresses further processing of the packet. Although
3843 // this is not a parsing error, returns false as this is in middle
3844 // of processing an ACK frame.
3845 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3846 return false;
3847 }
3848
3849 // Another one done.
3850 ack_block_count--;
3851 }
3852
fayang533cb1b2020-01-28 08:05:08 -08003853 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(block_low))) {
3854 set_detailed_error(
3855 "Error occurs when visitor finishes processing the ACK frame.");
3856 return false;
3857 }
3858
3859 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003860}
3861
3862bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3863 const QuicPacketHeader& header,
3864 QuicStopWaitingFrame* stop_waiting) {
3865 uint64_t least_unacked_delta;
3866 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3867 &least_unacked_delta)) {
3868 set_detailed_error("Unable to read least unacked delta.");
3869 return false;
3870 }
3871 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3872 set_detailed_error("Invalid unacked delta.");
3873 return false;
3874 }
3875 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3876
3877 return true;
3878}
3879
3880bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3881 QuicRstStreamFrame* frame) {
3882 if (!reader->ReadUInt32(&frame->stream_id)) {
3883 set_detailed_error("Unable to read stream_id.");
3884 return false;
3885 }
3886
3887 if (!reader->ReadUInt64(&frame->byte_offset)) {
3888 set_detailed_error("Unable to read rst stream sent byte offset.");
3889 return false;
3890 }
3891
3892 uint32_t error_code;
3893 if (!reader->ReadUInt32(&error_code)) {
3894 set_detailed_error("Unable to read rst stream error code.");
3895 return false;
3896 }
3897
3898 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3899 // Ignore invalid stream error code if any.
3900 error_code = QUIC_STREAM_LAST_ERROR;
3901 }
3902
3903 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3904
3905 return true;
3906}
3907
3908bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3909 QuicConnectionCloseFrame* frame) {
3910 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003911 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3912
QUICHE teama6ef0a62019-03-07 20:34:33 -05003913 if (!reader->ReadUInt32(&error_code)) {
3914 set_detailed_error("Unable to read connection close error code.");
3915 return false;
3916 }
3917
3918 if (error_code >= QUIC_LAST_ERROR) {
3919 // Ignore invalid QUIC error code if any.
3920 error_code = QUIC_LAST_ERROR;
3921 }
3922
fkastenholze9d71a82019-04-09 05:12:13 -07003923 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003924
fkastenholza14a7ae2019-08-07 05:21:22 -07003925 // For Google QUIC connection closes, copy the Google QUIC error code to
3926 // the extracted error code field so that the Google QUIC error code is always
3927 // available in extracted_error_code.
3928 frame->extracted_error_code = frame->quic_error_code;
3929
dmcardlecf0bfcf2019-12-13 08:08:21 -08003930 quiche::QuicheStringPiece error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003931 if (!reader->ReadStringPiece16(&error_details)) {
3932 set_detailed_error("Unable to read connection close error details.");
3933 return false;
3934 }
vasilvvc48c8712019-03-11 13:38:16 -07003935 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003936
3937 return true;
3938}
3939
3940bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3941 QuicGoAwayFrame* frame) {
3942 uint32_t error_code;
3943 if (!reader->ReadUInt32(&error_code)) {
3944 set_detailed_error("Unable to read go away error code.");
3945 return false;
3946 }
3947
3948 if (error_code >= QUIC_LAST_ERROR) {
3949 // Ignore invalid QUIC error code if any.
3950 error_code = QUIC_LAST_ERROR;
3951 }
3952 frame->error_code = static_cast<QuicErrorCode>(error_code);
3953
3954 uint32_t stream_id;
3955 if (!reader->ReadUInt32(&stream_id)) {
3956 set_detailed_error("Unable to read last good stream id.");
3957 return false;
3958 }
3959 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
3960
dmcardlecf0bfcf2019-12-13 08:08:21 -08003961 quiche::QuicheStringPiece reason_phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003962 if (!reader->ReadStringPiece16(&reason_phrase)) {
3963 set_detailed_error("Unable to read goaway reason.");
3964 return false;
3965 }
vasilvvc48c8712019-03-11 13:38:16 -07003966 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003967
3968 return true;
3969}
3970
3971bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
3972 QuicWindowUpdateFrame* frame) {
3973 if (!reader->ReadUInt32(&frame->stream_id)) {
3974 set_detailed_error("Unable to read stream_id.");
3975 return false;
3976 }
3977
renjietangd088eab2019-11-21 14:54:41 -08003978 if (!reader->ReadUInt64(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003979 set_detailed_error("Unable to read window byte_offset.");
3980 return false;
3981 }
3982
3983 return true;
3984}
3985
3986bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
3987 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07003988 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
3989 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05003990
3991 if (!reader->ReadUInt32(&frame->stream_id)) {
3992 set_detailed_error("Unable to read stream_id.");
3993 return false;
3994 }
3995
3996 return true;
3997}
3998
3999void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4000 QuicPaddingFrame* frame) {
4001 // Type byte has been read.
4002 frame->num_padding_bytes = 1;
4003 uint8_t next_byte;
4004 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4005 reader->ReadBytes(&next_byte, 1);
4006 DCHECK_EQ(0x00, next_byte);
4007 ++frame->num_padding_bytes;
4008 }
4009}
4010
4011bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4012 bool no_message_length,
4013 QuicMessageFrame* frame) {
4014 if (no_message_length) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08004015 quiche::QuicheStringPiece remaining(reader->ReadRemainingPayload());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004016 frame->data = remaining.data();
4017 frame->message_length = remaining.length();
4018 return true;
4019 }
4020
4021 uint64_t message_length;
4022 if (!reader->ReadVarInt62(&message_length)) {
4023 set_detailed_error("Unable to read message length");
4024 return false;
4025 }
4026
dmcardlecf0bfcf2019-12-13 08:08:21 -08004027 quiche::QuicheStringPiece message_piece;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004028 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4029 set_detailed_error("Unable to read message data");
4030 return false;
4031 }
4032
4033 frame->data = message_piece.data();
4034 frame->message_length = message_length;
4035
4036 return true;
4037}
4038
4039// static
dmcardlecf0bfcf2019-12-13 08:08:21 -08004040quiche::QuicheStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004041 QuicTransportVersion version,
4042 const QuicEncryptedPacket& encrypted,
4043 QuicConnectionIdLength destination_connection_id_length,
4044 QuicConnectionIdLength source_connection_id_length,
4045 bool includes_version,
4046 bool includes_diversification_nonce,
4047 QuicPacketNumberLength packet_number_length,
4048 QuicVariableLengthIntegerLength retry_token_length_length,
4049 uint64_t retry_token_length,
4050 QuicVariableLengthIntegerLength length_length) {
4051 // TODO(ianswett): This is identical to QuicData::AssociatedData.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004052 return quiche::QuicheStringPiece(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004053 encrypted.data(),
4054 GetStartOfEncryptedData(version, destination_connection_id_length,
4055 source_connection_id_length, includes_version,
4056 includes_diversification_nonce,
4057 packet_number_length, retry_token_length_length,
4058 retry_token_length, length_length));
4059}
4060
4061void QuicFramer::SetDecrypter(EncryptionLevel level,
4062 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004063 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004064 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004065 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004066 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004067 << EncryptionLevelToString(decrypter_level_) << " to "
4068 << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004069 decrypter_[decrypter_level_] = nullptr;
4070 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004071 decrypter_level_ = level;
4072}
4073
4074void QuicFramer::SetAlternativeDecrypter(
4075 EncryptionLevel level,
4076 std::unique_ptr<QuicDecrypter> decrypter,
4077 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004078 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004079 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004080 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004081 << EncryptionLevelToString(alternative_decrypter_level_)
4082 << " to " << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004083 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4084 decrypter_[alternative_decrypter_level_] = nullptr;
4085 }
4086 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004087 alternative_decrypter_level_ = level;
4088 alternative_decrypter_latch_ = latch_once_used;
4089}
4090
zhongyi546cc452019-04-12 15:27:49 -07004091void QuicFramer::InstallDecrypter(EncryptionLevel level,
4092 std::unique_ptr<QuicDecrypter> decrypter) {
4093 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004094 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004095 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004096 decrypter_[level] = std::move(decrypter);
4097}
4098
4099void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4100 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004101 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004102 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004103 decrypter_[level] = nullptr;
4104}
4105
4106const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4107 DCHECK(version_.KnowsWhichDecrypterToUse());
4108 return decrypter_[level].get();
4109}
4110
QUICHE teama6ef0a62019-03-07 20:34:33 -05004111const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004112 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004113}
4114
4115const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004116 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4117 return nullptr;
4118 }
4119 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004120}
4121
4122void QuicFramer::SetEncrypter(EncryptionLevel level,
4123 std::unique_ptr<QuicEncrypter> encrypter) {
4124 DCHECK_GE(level, 0);
4125 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
dschinazi4b5a68a2019-08-15 15:45:36 -07004126 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004127 << EncryptionLevelToString(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004128 encrypter_[level] = std::move(encrypter);
4129}
4130
nharper4a5a76c2019-09-13 13:44:37 -07004131void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) {
4132 CrypterPair crypters;
4133 CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id,
4134 &crypters);
4135 encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter);
4136 decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter);
4137}
4138
QUICHE teama6ef0a62019-03-07 20:34:33 -05004139size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4140 QuicPacketNumber packet_number,
4141 size_t ad_len,
4142 size_t total_len,
4143 size_t buffer_len,
4144 char* buffer) {
4145 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004146 if (encrypter_[level] == nullptr) {
4147 QUIC_BUG << ENDPOINT
4148 << "Attempted to encrypt in place without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004149 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004150 RaiseError(QUIC_ENCRYPTION_FAILURE);
4151 return 0;
4152 }
4153
QUICHE teama6ef0a62019-03-07 20:34:33 -05004154 size_t output_length = 0;
4155 if (!encrypter_[level]->EncryptPacket(
4156 packet_number.ToUint64(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08004157 quiche::QuicheStringPiece(buffer, ad_len), // Associated data
4158 quiche::QuicheStringPiece(buffer + ad_len,
4159 total_len - ad_len), // Plaintext
4160 buffer + ad_len, // Destination buffer
QUICHE teama6ef0a62019-03-07 20:34:33 -05004161 &output_length, buffer_len - ad_len)) {
4162 RaiseError(QUIC_ENCRYPTION_FAILURE);
4163 return 0;
4164 }
nharper55fa6132019-05-07 19:37:21 -07004165 if (version_.HasHeaderProtection() &&
4166 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4167 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4168 RaiseError(QUIC_ENCRYPTION_FAILURE);
4169 return 0;
4170 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004171
4172 return ad_len + output_length;
4173}
4174
nharper55fa6132019-05-07 19:37:21 -07004175namespace {
4176
4177const size_t kHPSampleLen = 16;
4178
4179constexpr bool IsLongHeader(uint8_t type_byte) {
4180 return (type_byte & FLAGS_LONG_HEADER) != 0;
4181}
4182
4183} // namespace
4184
4185bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4186 char* buffer,
4187 size_t buffer_len,
4188 size_t ad_len) {
4189 QuicDataReader buffer_reader(buffer, buffer_len);
4190 QuicDataWriter buffer_writer(buffer_len, buffer);
4191 // The sample starts 4 bytes after the start of the packet number.
4192 if (ad_len < last_written_packet_number_length_) {
4193 return false;
4194 }
4195 size_t pn_offset = ad_len - last_written_packet_number_length_;
4196 // Sample the ciphertext and generate the mask to use for header protection.
4197 size_t sample_offset = pn_offset + 4;
4198 QuicDataReader sample_reader(buffer, buffer_len);
dmcardlecf0bfcf2019-12-13 08:08:21 -08004199 quiche::QuicheStringPiece sample;
nharper55fa6132019-05-07 19:37:21 -07004200 if (!sample_reader.Seek(sample_offset) ||
4201 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4202 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4203 << ", sample len: " << kHPSampleLen
4204 << ", buffer len: " << buffer_len;
4205 return false;
4206 }
4207
4208 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4209 if (mask.empty()) {
4210 QUIC_BUG << "Unable to generate header protection mask.";
4211 return false;
4212 }
4213 QuicDataReader mask_reader(mask.data(), mask.size());
4214
4215 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4216 uint8_t bitmask = 0x1f;
4217 uint8_t type_byte;
4218 if (!buffer_reader.ReadUInt8(&type_byte)) {
4219 return false;
4220 }
4221 QuicLongHeaderType header_type;
4222 if (IsLongHeader(type_byte)) {
4223 bitmask = 0x0f;
fayang36825da2019-08-21 14:01:27 -07004224 if (!GetLongHeaderType(type_byte, &header_type)) {
nharper55fa6132019-05-07 19:37:21 -07004225 return false;
4226 }
4227 }
4228 uint8_t mask_byte;
4229 if (!mask_reader.ReadUInt8(&mask_byte) ||
4230 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4231 return false;
4232 }
4233
4234 // Adjust |pn_offset| to account for the diversification nonce.
4235 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4236 perspective_ == Perspective::IS_SERVER &&
4237 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4238 if (pn_offset <= kDiversificationNonceSize) {
4239 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4240 return false;
4241 }
4242 pn_offset -= kDiversificationNonceSize;
4243 }
4244 // Advance the reader and writer to the packet number. Both the reader and
4245 // writer have each read/written one byte.
4246 if (!buffer_writer.Seek(pn_offset - 1) ||
4247 !buffer_reader.Seek(pn_offset - 1)) {
4248 return false;
4249 }
4250 // Apply the rest of the mask to the packet number.
4251 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4252 uint8_t buffer_byte;
4253 uint8_t mask_byte;
4254 if (!mask_reader.ReadUInt8(&mask_byte) ||
4255 !buffer_reader.ReadUInt8(&buffer_byte) ||
4256 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4257 return false;
4258 }
4259 }
4260 return true;
4261}
4262
4263bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4264 const QuicEncryptedPacket& packet,
4265 QuicPacketHeader* header,
4266 uint64_t* full_packet_number,
4267 std::vector<char>* associated_data) {
4268 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4269 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4270 if (decrypter == nullptr) {
4271 QUIC_DVLOG(1)
dschinazi4b5a68a2019-08-15 15:45:36 -07004272 << ENDPOINT
nharper55fa6132019-05-07 19:37:21 -07004273 << "No decrypter available for removing header protection at level "
dschinazief79a5f2019-10-04 10:32:54 -07004274 << EncryptionLevelToString(expected_decryption_level);
nharper55fa6132019-05-07 19:37:21 -07004275 return false;
4276 }
4277
4278 bool has_diversification_nonce =
4279 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4280 header->long_packet_type == ZERO_RTT_PROTECTED &&
4281 perspective_ == Perspective::IS_CLIENT &&
4282 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4283
4284 // Read a sample from the ciphertext and compute the mask to use for header
4285 // protection.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004286 quiche::QuicheStringPiece remaining_packet = reader->PeekRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07004287 QuicDataReader sample_reader(remaining_packet);
4288
4289 // The sample starts 4 bytes after the start of the packet number.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004290 quiche::QuicheStringPiece pn;
nharper55fa6132019-05-07 19:37:21 -07004291 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4292 QUIC_DVLOG(1) << "Not enough data to sample";
4293 return false;
4294 }
4295 if (has_diversification_nonce) {
4296 // In Google QUIC, the diversification nonce comes between the packet number
4297 // and the sample.
4298 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4299 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4300 return false;
4301 }
4302 }
4303 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4304 QuicDataReader mask_reader(mask.data(), mask.size());
4305 if (mask.empty()) {
4306 QUIC_DVLOG(1) << "Failed to compute mask";
4307 return false;
4308 }
4309
4310 // Unmask the rest of the type byte.
4311 uint8_t bitmask = 0x1f;
4312 if (IsLongHeader(header->type_byte)) {
4313 bitmask = 0x0f;
4314 }
4315 uint8_t mask_byte;
4316 if (!mask_reader.ReadUInt8(&mask_byte)) {
4317 QUIC_DVLOG(1) << "No first byte to read from mask";
4318 return false;
4319 }
4320 header->type_byte ^= (mask_byte & bitmask);
4321
4322 // Compute the packet number length.
4323 header->packet_number_length =
4324 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4325
4326 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
bnc4e9283d2019-12-17 07:08:57 -08004327 QuicDataWriter pn_writer(QUICHE_ARRAYSIZE(pn_buffer), pn_buffer);
nharper55fa6132019-05-07 19:37:21 -07004328
4329 // Read the (protected) packet number from the reader and unmask the packet
4330 // number.
4331 for (size_t i = 0; i < header->packet_number_length; ++i) {
4332 uint8_t protected_pn_byte, mask_byte;
4333 if (!mask_reader.ReadUInt8(&mask_byte) ||
4334 !reader->ReadUInt8(&protected_pn_byte) ||
4335 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4336 QUIC_DVLOG(1) << "Failed to unmask packet number";
4337 return false;
4338 }
4339 }
4340 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4341 QuicPacketNumber base_packet_number;
4342 if (supports_multiple_packet_number_spaces_) {
4343 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4344 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4345 return false;
4346 }
4347 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4348 } else {
4349 base_packet_number = largest_packet_number_;
4350 }
4351 if (!ProcessAndCalculatePacketNumber(
4352 &packet_number_reader, header->packet_number_length,
4353 base_packet_number, full_packet_number)) {
4354 return false;
4355 }
4356
4357 // Get the associated data, and apply the same unmasking operations to it.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004358 quiche::QuicheStringPiece ad = GetAssociatedDataFromEncryptedPacket(
nharper55fa6132019-05-07 19:37:21 -07004359 version_.transport_version, packet,
4360 GetIncludedDestinationConnectionIdLength(*header),
4361 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4362 has_diversification_nonce, header->packet_number_length,
4363 header->retry_token_length_length, header->retry_token.length(),
4364 header->length_length);
4365 *associated_data = std::vector<char>(ad.begin(), ad.end());
4366 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4367
4368 // Apply the unmasked type byte and packet number to |associated_data|.
4369 if (!ad_writer.WriteUInt8(header->type_byte)) {
4370 return false;
4371 }
4372 // Put the packet number at the end of the AD, or if there's a diversification
4373 // nonce, before that (which is at the end of the AD).
4374 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4375 if (has_diversification_nonce) {
4376 seek_len -= kDiversificationNonceSize;
4377 }
4378 if (!ad_writer.Seek(seek_len) ||
4379 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4380 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4381 return false;
4382 }
4383
4384 return true;
4385}
4386
QUICHE teama6ef0a62019-03-07 20:34:33 -05004387size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4388 QuicPacketNumber packet_number,
4389 const QuicPacket& packet,
4390 char* buffer,
4391 size_t buffer_len) {
4392 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004393 if (encrypter_[level] == nullptr) {
4394 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004395 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004396 RaiseError(QUIC_ENCRYPTION_FAILURE);
4397 return 0;
4398 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004399
dmcardlecf0bfcf2019-12-13 08:08:21 -08004400 quiche::QuicheStringPiece associated_data =
QUICHE teama6ef0a62019-03-07 20:34:33 -05004401 packet.AssociatedData(version_.transport_version);
4402 // Copy in the header, because the encrypter only populates the encrypted
4403 // plaintext content.
4404 const size_t ad_len = associated_data.length();
4405 memmove(buffer, associated_data.data(), ad_len);
4406 // Encrypt the plaintext into the buffer.
4407 size_t output_length = 0;
4408 if (!encrypter_[level]->EncryptPacket(
4409 packet_number.ToUint64(), associated_data,
4410 packet.Plaintext(version_.transport_version), buffer + ad_len,
4411 &output_length, buffer_len - ad_len)) {
4412 RaiseError(QUIC_ENCRYPTION_FAILURE);
4413 return 0;
4414 }
nharper55fa6132019-05-07 19:37:21 -07004415 if (version_.HasHeaderProtection() &&
4416 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4417 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4418 RaiseError(QUIC_ENCRYPTION_FAILURE);
4419 return 0;
4420 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004421
4422 return ad_len + output_length;
4423}
4424
4425size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4426 size_t plaintext_size) const {
4427 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4428}
4429
4430size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4431 // In order to keep the code simple, we don't have the current encryption
4432 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4433 size_t min_plaintext_size = ciphertext_size;
4434
QUICHE team6987b4a2019-03-15 16:23:04 -07004435 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004436 if (encrypter_[i] != nullptr) {
4437 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4438 if (size < min_plaintext_size) {
4439 min_plaintext_size = size;
4440 }
4441 }
4442 }
4443
4444 return min_plaintext_size;
4445}
4446
dmcardlecf0bfcf2019-12-13 08:08:21 -08004447bool QuicFramer::DecryptPayload(quiche::QuicheStringPiece encrypted,
4448 quiche::QuicheStringPiece associated_data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004449 const QuicPacketHeader& header,
4450 char* decrypted_buffer,
4451 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004452 size_t* decrypted_length,
4453 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004454 if (!EncryptionLevelIsValid(decrypter_level_)) {
4455 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4456 return false;
4457 }
zhongyi546cc452019-04-12 15:27:49 -07004458 EncryptionLevel level = decrypter_level_;
4459 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004460 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004461 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004462 if (header.form == GOOGLE_QUIC_PACKET) {
4463 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4464 "knows which decrypter to use";
4465 return false;
4466 }
zhongyi546cc452019-04-12 15:27:49 -07004467 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004468 if (!EncryptionLevelIsValid(level)) {
4469 QUIC_BUG << "Attempted to decrypt with bad level";
4470 return false;
4471 }
zhongyi546cc452019-04-12 15:27:49 -07004472 decrypter = decrypter_[level].get();
4473 if (decrypter == nullptr) {
4474 return false;
4475 }
4476 if (level == ENCRYPTION_ZERO_RTT &&
4477 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4478 decrypter->SetDiversificationNonce(*header.nonce);
4479 }
4480 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004481 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4482 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4483 return false;
4484 }
QUICHE team76086e42019-03-25 15:12:29 -07004485 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4486 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004487
nharper855d2172019-05-02 16:17:46 -07004488 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004489 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4490 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004491 return false;
4492 }
zhongyi546cc452019-04-12 15:27:49 -07004493
4494 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004495 header.packet_number.ToUint64(), associated_data, encrypted,
4496 decrypted_buffer, decrypted_length, buffer_length);
4497 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004498 visitor_->OnDecryptedPacket(level);
4499 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004500 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004501 if (header.nonce != nullptr) {
4502 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004503 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004504 }
4505 bool try_alternative_decryption = true;
4506 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4507 if (perspective_ == Perspective::IS_CLIENT) {
4508 if (header.nonce == nullptr) {
4509 // Can not use INITIAL decryption without a diversification nonce.
4510 try_alternative_decryption = false;
4511 }
4512 } else {
4513 DCHECK(header.nonce == nullptr);
4514 }
4515 }
4516
4517 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004518 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004519 header.packet_number.ToUint64(), associated_data, encrypted,
4520 decrypted_buffer, decrypted_length, buffer_length);
4521 }
4522 if (success) {
4523 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004524 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004525 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004526 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4527 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4528 "alternative_decrypter_level_";
4529 return false;
4530 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004531 // Switch to the alternative decrypter and latch so that we cannot
4532 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004533 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004534 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004535 } else {
4536 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004537 EncryptionLevel level = alternative_decrypter_level_;
4538 alternative_decrypter_level_ = decrypter_level_;
4539 decrypter_level_ = level;
4540 }
4541 }
4542 }
4543
4544 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004545 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004546 return false;
4547 }
4548
4549 return true;
4550}
4551
4552size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4553 // Type byte, largest_acked, and delay_time are straight-forward.
4554 size_t ack_frame_size = kQuicFrameTypeSize;
4555 QuicPacketNumber largest_acked = LargestAcked(frame);
4556 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4557 uint64_t ack_delay_time_us;
4558 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004559 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004560 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4561
4562 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4563 // then the ecn counters are included...
4564 if (frame.ecn_counters_populated &&
4565 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4566 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4567 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4568 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4569 }
4570
4571 // The rest (ack_block_count, first_ack_block, and additional ack
4572 // blocks, if any) depends:
4573 uint64_t ack_block_count = frame.packets.NumIntervals();
4574 if (ack_block_count == 0) {
4575 // If the QuicAckFrame has no Intervals, then it is interpreted
4576 // as an ack of a single packet at QuicAckFrame.largest_acked.
4577 // The resulting ack will consist of only the frame's
4578 // largest_ack & first_ack_block fields. The first ack block will be 0
4579 // (indicating a single packet) and the ack block_count will be 0.
4580 // Each 0 takes 1 byte when VarInt62 encoded.
4581 ack_frame_size += 2;
4582 return ack_frame_size;
4583 }
4584
4585 auto itr = frame.packets.rbegin();
4586 QuicPacketNumber ack_block_largest = largest_acked;
4587 QuicPacketNumber ack_block_smallest;
4588 if ((itr->max() - 1) == largest_acked) {
4589 // If largest_acked + 1 is equal to the Max() of the first Interval
4590 // in the QuicAckFrame then the first Interval is the first ack block of the
4591 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4592 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4593 // the remaining Intervals are encoded in additional ack blocks in the
4594 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4595 // Intervals - 1.
4596 ack_block_smallest = itr->min();
4597 itr++;
4598 ack_block_count--;
4599 } else {
4600 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4601 // the first Interval then it is interpreted as acking a single
4602 // packet at QuicAckFrame.largest_acked, with additional
4603 // Intervals indicating additional ack blocks. The encoding is
4604 // a) The packet's largest_acked is the QuicAckFrame's largest
4605 // acked,
4606 // b) the first ack block size is 0,
4607 // c) The packet's ack_block_count is the number of QuicAckFrame
4608 // Intervals, and
4609 // d) The QuicAckFrame Intervals are encoded in additional ack
4610 // blocks in the packet.
4611 ack_block_smallest = largest_acked;
4612 }
4613 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4614 ack_frame_size += ack_block_count_size;
4615
4616 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4617 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4618 ack_frame_size += first_ack_block_size;
4619
4620 // Account for the remaining Intervals, if any.
4621 while (ack_block_count != 0) {
4622 uint64_t gap_size = ack_block_smallest - itr->max();
4623 // Decrement per the protocol specification
4624 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4625 ack_frame_size += size_of_gap_size;
4626
4627 uint64_t block_size = itr->max() - itr->min();
4628 // Decrement per the protocol specification
4629 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4630 ack_frame_size += size_of_block_size;
4631
4632 ack_block_smallest = itr->min();
4633 itr++;
4634 ack_block_count--;
4635 }
4636
4637 return ack_frame_size;
4638}
4639
4640size_t QuicFramer::GetAckFrameSize(
4641 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004642 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004643 DCHECK(!ack.packets.Empty());
4644 size_t ack_size = 0;
4645
fkastenholz305e1732019-06-18 05:01:22 -07004646 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004647 return GetIetfAckFrameSize(ack);
4648 }
4649 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4650 QuicPacketNumberLength largest_acked_length =
renjietang488201d2019-12-17 13:40:49 -08004651 GetMinPacketNumberLength(LargestAcked(ack));
4652 QuicPacketNumberLength ack_block_length =
4653 GetMinPacketNumberLength(QuicPacketNumber(ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004654
4655 ack_size =
4656 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4657 // First ack block length.
4658 ack_size += ack_block_length;
4659 if (ack_info.num_ack_blocks != 0) {
4660 ack_size += kNumberOfAckBlocksSize;
4661 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4662 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4663 }
4664
4665 // Include timestamps.
4666 if (process_timestamps_) {
4667 ack_size += GetAckFrameTimeStampSize(ack);
4668 }
4669
4670 return ack_size;
4671}
4672
4673size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4674 if (ack.received_packet_times.empty()) {
4675 return 0;
4676 }
4677
4678 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4679 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4680 (ack.received_packet_times.size() - 1);
4681}
4682
4683size_t QuicFramer::ComputeFrameLength(
4684 const QuicFrame& frame,
4685 bool last_frame_in_packet,
4686 QuicPacketNumberLength packet_number_length) {
4687 switch (frame.type) {
4688 case STREAM_FRAME:
4689 return GetMinStreamFrameSize(
4690 version_.transport_version, frame.stream_frame.stream_id,
4691 frame.stream_frame.offset, last_frame_in_packet,
4692 frame.stream_frame.data_length) +
4693 frame.stream_frame.data_length;
4694 case CRYPTO_FRAME:
4695 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4696 frame.crypto_frame->data_length) +
4697 frame.crypto_frame->data_length;
4698 case ACK_FRAME: {
4699 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4700 }
4701 case STOP_WAITING_FRAME:
renjietang488201d2019-12-17 13:40:49 -08004702 return GetStopWaitingFrameSize(packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004703 case MTU_DISCOVERY_FRAME:
4704 // MTU discovery frames are serialized as ping frames.
4705 return kQuicFrameTypeSize;
4706 case MESSAGE_FRAME:
4707 return GetMessageFrameSize(version_.transport_version,
4708 last_frame_in_packet,
4709 frame.message_frame->message_length);
4710 case PADDING_FRAME:
4711 DCHECK(false);
4712 return 0;
4713 default:
4714 return GetRetransmittableControlFrameSize(version_.transport_version,
4715 frame);
4716 }
4717}
4718
4719bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4720 bool last_frame_in_packet,
4721 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004722 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004723 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4724 }
4725 uint8_t type_byte = 0;
4726 switch (frame.type) {
4727 case STREAM_FRAME:
4728 type_byte =
4729 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4730 break;
4731 case ACK_FRAME:
4732 return true;
4733 case MTU_DISCOVERY_FRAME:
4734 type_byte = static_cast<uint8_t>(PING_FRAME);
4735 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004736 case NEW_CONNECTION_ID_FRAME:
4737 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004738 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004739 return RaiseError(QUIC_INTERNAL_ERROR);
4740 case RETIRE_CONNECTION_ID_FRAME:
4741 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004742 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004743 return RaiseError(QUIC_INTERNAL_ERROR);
4744 case NEW_TOKEN_FRAME:
4745 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004746 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004747 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004748 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004749 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004750 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004751 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004752 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004753 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004754 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004755 return RaiseError(QUIC_INTERNAL_ERROR);
4756 case PATH_RESPONSE_FRAME:
4757 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004758 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004759 return RaiseError(QUIC_INTERNAL_ERROR);
4760 case PATH_CHALLENGE_FRAME:
4761 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004762 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004763 return RaiseError(QUIC_INTERNAL_ERROR);
4764 case STOP_SENDING_FRAME:
4765 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004766 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004767 return RaiseError(QUIC_INTERNAL_ERROR);
4768 case MESSAGE_FRAME:
4769 return true;
4770
4771 default:
4772 type_byte = static_cast<uint8_t>(frame.type);
4773 break;
4774 }
4775
4776 return writer->WriteUInt8(type_byte);
4777}
4778
4779bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4780 bool last_frame_in_packet,
4781 QuicDataWriter* writer) {
4782 uint8_t type_byte = 0;
4783 switch (frame.type) {
4784 case PADDING_FRAME:
4785 type_byte = IETF_PADDING;
4786 break;
4787 case RST_STREAM_FRAME:
4788 type_byte = IETF_RST_STREAM;
4789 break;
4790 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004791 switch (frame.connection_close_frame->close_type) {
4792 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4793 type_byte = IETF_APPLICATION_CLOSE;
4794 break;
4795 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4796 type_byte = IETF_CONNECTION_CLOSE;
4797 break;
4798 default:
4799 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4800 return RaiseError(QUIC_INTERNAL_ERROR);
4801 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004802 break;
4803 case GOAWAY_FRAME:
4804 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004805 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004806 return RaiseError(QUIC_INTERNAL_ERROR);
4807 case WINDOW_UPDATE_FRAME:
4808 // Depending on whether there is a stream ID or not, will be either a
4809 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4810 if (frame.window_update_frame->stream_id ==
4811 QuicUtils::GetInvalidStreamId(transport_version())) {
4812 type_byte = IETF_MAX_DATA;
4813 } else {
4814 type_byte = IETF_MAX_STREAM_DATA;
4815 }
4816 break;
4817 case BLOCKED_FRAME:
4818 if (frame.blocked_frame->stream_id ==
4819 QuicUtils::GetInvalidStreamId(transport_version())) {
ianswett2f077442019-12-12 11:51:24 -08004820 type_byte = IETF_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004821 } else {
ianswett2f077442019-12-12 11:51:24 -08004822 type_byte = IETF_STREAM_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004823 }
4824 break;
4825 case STOP_WAITING_FRAME:
4826 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004827 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004828 return RaiseError(QUIC_INTERNAL_ERROR);
4829 case PING_FRAME:
4830 type_byte = IETF_PING;
4831 break;
4832 case STREAM_FRAME:
4833 type_byte =
4834 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4835 break;
4836 case ACK_FRAME:
4837 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4838 // in the buffer.
4839 return true;
4840 case MTU_DISCOVERY_FRAME:
4841 // The path MTU discovery frame is encoded as a PING frame on the wire.
4842 type_byte = IETF_PING;
4843 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004844 case NEW_CONNECTION_ID_FRAME:
4845 type_byte = IETF_NEW_CONNECTION_ID;
4846 break;
4847 case RETIRE_CONNECTION_ID_FRAME:
4848 type_byte = IETF_RETIRE_CONNECTION_ID;
4849 break;
4850 case NEW_TOKEN_FRAME:
4851 type_byte = IETF_NEW_TOKEN;
4852 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004853 case MAX_STREAMS_FRAME:
4854 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004855 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004856 } else {
4857 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004858 }
4859 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004860 case STREAMS_BLOCKED_FRAME:
4861 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004862 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004863 } else {
4864 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004865 }
4866 break;
4867 case PATH_RESPONSE_FRAME:
4868 type_byte = IETF_PATH_RESPONSE;
4869 break;
4870 case PATH_CHALLENGE_FRAME:
4871 type_byte = IETF_PATH_CHALLENGE;
4872 break;
4873 case STOP_SENDING_FRAME:
4874 type_byte = IETF_STOP_SENDING;
4875 break;
4876 case MESSAGE_FRAME:
4877 return true;
4878 case CRYPTO_FRAME:
4879 type_byte = IETF_CRYPTO;
4880 break;
fayang01062942020-01-22 07:23:23 -08004881 case HANDSHAKE_DONE_FRAME:
4882 type_byte = IETF_HANDSHAKE_DONE;
4883 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004884 default:
4885 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4886 << frame.type;
4887 return false;
4888 }
4889 return writer->WriteUInt8(type_byte);
4890}
4891
4892// static
4893bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4894 QuicPacketNumber packet_number,
4895 QuicDataWriter* writer) {
4896 DCHECK(packet_number.IsInitialized());
4897 if (!IsValidPacketNumberLength(packet_number_length)) {
4898 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4899 return false;
4900 }
4901 return writer->WriteBytesToUInt64(packet_number_length,
4902 packet_number.ToUint64());
4903}
4904
4905// static
4906bool QuicFramer::AppendStreamId(size_t stream_id_length,
4907 QuicStreamId stream_id,
4908 QuicDataWriter* writer) {
4909 if (stream_id_length == 0 || stream_id_length > 4) {
4910 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4911 return false;
4912 }
4913 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4914}
4915
4916// static
4917bool QuicFramer::AppendStreamOffset(size_t offset_length,
4918 QuicStreamOffset offset,
4919 QuicDataWriter* writer) {
4920 if (offset_length == 1 || offset_length > 8) {
4921 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4922 return false;
4923 }
4924
4925 return writer->WriteBytesToUInt64(offset_length, offset);
4926}
4927
4928// static
4929bool QuicFramer::AppendAckBlock(uint8_t gap,
4930 QuicPacketNumberLength length_length,
4931 uint64_t length,
4932 QuicDataWriter* writer) {
4933 if (length == 0) {
4934 if (!IsValidPacketNumberLength(length_length)) {
4935 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4936 return false;
4937 }
4938 return writer->WriteUInt8(gap) &&
4939 writer->WriteBytesToUInt64(length_length, length);
4940 }
4941 return writer->WriteUInt8(gap) &&
4942 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4943}
4944
4945bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4946 bool no_stream_frame_length,
4947 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004948 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004949 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4950 }
4951 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4952 writer)) {
4953 QUIC_BUG << "Writing stream id size failed.";
4954 return false;
4955 }
renjietang488201d2019-12-17 13:40:49 -08004956 if (!AppendStreamOffset(GetStreamOffsetSize(frame.offset), frame.offset,
4957 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004958 QUIC_BUG << "Writing offset size failed.";
4959 return false;
4960 }
4961 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07004962 static_assert(
wubeff50282019-06-19 09:04:30 -07004963 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07004964 std::numeric_limits<uint16_t>::max(),
4965 "If frame.data_length can hold more than a uint16_t than we need to "
4966 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
4967 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004968 QUIC_BUG << "Writing stream frame length failed";
4969 return false;
4970 }
4971 }
4972
4973 if (data_producer_ != nullptr) {
4974 DCHECK_EQ(nullptr, frame.data_buffer);
4975 if (frame.data_length == 0) {
4976 return true;
4977 }
4978 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
4979 frame.data_length,
4980 writer) != WRITE_SUCCESS) {
4981 QUIC_BUG << "Writing frame data failed.";
4982 return false;
4983 }
4984 return true;
4985 }
4986
4987 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
4988 QUIC_BUG << "Writing frame data failed.";
4989 return false;
4990 }
4991 return true;
4992}
4993
QUICHE teama6ef0a62019-03-07 20:34:33 -05004994bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
4995 QuicDataWriter* writer) {
4996 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
4997 set_detailed_error("Writing token length failed.");
4998 return false;
4999 }
5000 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5001 set_detailed_error("Writing token buffer failed.");
5002 return false;
5003 }
5004 return true;
5005}
5006
5007bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5008 QuicNewTokenFrame* frame) {
5009 uint64_t length;
5010 if (!reader->ReadVarInt62(&length)) {
5011 set_detailed_error("Unable to read new token length.");
5012 return false;
5013 }
5014 if (length > kMaxNewTokenTokenLength) {
5015 set_detailed_error("Token length larger than maximum.");
5016 return false;
5017 }
5018
dmcardlecf0bfcf2019-12-13 08:08:21 -08005019 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
5020 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005021 if (!reader->ReadStringPiece(&data, length)) {
5022 set_detailed_error("Unable to read new token data.");
5023 return false;
5024 }
vasilvvc48c8712019-03-11 13:38:16 -07005025 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005026 return true;
5027}
5028
5029// Add a new ietf-format stream frame.
5030// Bits controlling whether there is a frame-length and frame-offset
5031// are in the QuicStreamFrame.
5032bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5033 bool last_frame_in_packet,
5034 QuicDataWriter* writer) {
5035 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5036 set_detailed_error("Writing stream id failed.");
5037 return false;
5038 }
5039
5040 if (frame.offset != 0) {
5041 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5042 set_detailed_error("Writing data offset failed.");
5043 return false;
5044 }
5045 }
5046
5047 if (!last_frame_in_packet) {
5048 if (!writer->WriteVarInt62(frame.data_length)) {
5049 set_detailed_error("Writing data length failed.");
5050 return false;
5051 }
5052 }
5053
5054 if (frame.data_length == 0) {
5055 return true;
5056 }
5057 if (data_producer_ == nullptr) {
5058 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5059 set_detailed_error("Writing frame data failed.");
5060 return false;
5061 }
5062 } else {
5063 DCHECK_EQ(nullptr, frame.data_buffer);
5064
5065 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5066 frame.data_length,
5067 writer) != WRITE_SUCCESS) {
5068 set_detailed_error("Writing frame data failed.");
5069 return false;
5070 }
5071 }
5072 return true;
5073}
5074
5075bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5076 QuicDataWriter* writer) {
5077 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5078 set_detailed_error("Writing data offset failed.");
5079 return false;
5080 }
5081 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5082 set_detailed_error("Writing data length failed.");
5083 return false;
5084 }
5085 if (data_producer_ == nullptr) {
5086 if (frame.data_buffer == nullptr ||
5087 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5088 set_detailed_error("Writing frame data failed.");
5089 return false;
5090 }
5091 } else {
5092 DCHECK_EQ(nullptr, frame.data_buffer);
5093 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5094 frame.data_length, writer)) {
5095 return false;
5096 }
5097 }
5098 return true;
5099}
5100
5101void QuicFramer::set_version(const ParsedQuicVersion version) {
5102 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5103 version_ = version;
5104}
5105
5106bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5107 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005108 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005109 return AppendIetfAckFrameAndTypeByte(frame, writer);
5110 }
5111
5112 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5113 QuicPacketNumber largest_acked = LargestAcked(frame);
5114 QuicPacketNumberLength largest_acked_length =
renjietang488201d2019-12-17 13:40:49 -08005115 GetMinPacketNumberLength(largest_acked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005116 QuicPacketNumberLength ack_block_length =
renjietang488201d2019-12-17 13:40:49 -08005117 GetMinPacketNumberLength(QuicPacketNumber(new_ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005118 // Calculate available bytes for timestamps and ack blocks.
5119 int32_t available_timestamp_and_ack_block_bytes =
5120 writer->capacity() - writer->length() - ack_block_length -
5121 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5122 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5123 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5124
5125 // Write out the type byte by setting the low order bits and doing shifts
5126 // to make room for the next bit flags to be set.
5127 // Whether there are multiple ack blocks.
5128 uint8_t type_byte = 0;
5129 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5130 kQuicHasMultipleAckBlocksOffset);
5131
5132 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5133 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5134
5135 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5136 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5137
5138 type_byte |= kQuicFrameTypeAckMask;
5139
5140 if (!writer->WriteUInt8(type_byte)) {
5141 return false;
5142 }
5143
5144 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5145 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5146
5147 // Number of ack blocks.
5148 size_t num_ack_blocks =
5149 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5150 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5151 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5152 }
5153
5154 // Largest acked.
5155 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5156 return false;
5157 }
5158
5159 // Largest acked delta time.
5160 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5161 if (!frame.ack_delay_time.IsInfinite()) {
5162 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5163 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5164 }
5165 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5166 return false;
5167 }
5168
5169 if (num_ack_blocks > 0) {
5170 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5171 return false;
5172 }
5173 }
5174
5175 // First ack block length.
5176 if (!AppendPacketNumber(ack_block_length,
5177 QuicPacketNumber(new_ack_info.first_block_length),
5178 writer)) {
5179 return false;
5180 }
5181
5182 // Ack blocks.
5183 if (num_ack_blocks > 0) {
5184 size_t num_ack_blocks_written = 0;
5185 // Append, in descending order from the largest ACKed packet, a series of
5186 // ACK blocks that represents the successfully acknoweldged packets. Each
5187 // appended gap/block length represents a descending delta from the previous
5188 // block. i.e.:
5189 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5190 // For gaps larger than can be represented by a single encoded gap, a 0
5191 // length gap of the maximum is used, i.e.:
5192 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5193 auto itr = frame.packets.rbegin();
5194 QuicPacketNumber previous_start = itr->min();
5195 ++itr;
5196
5197 for (;
5198 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5199 previous_start = itr->min(), ++itr) {
5200 const auto& interval = *itr;
5201 const uint64_t total_gap = previous_start - interval.max();
5202 const size_t num_encoded_gaps =
5203 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5204 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005205
5206 // Append empty ACK blocks because the gap is longer than a single gap.
5207 for (size_t i = 1;
5208 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5209 ++i) {
5210 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5211 ack_block_length, 0, writer)) {
5212 return false;
5213 }
5214 ++num_ack_blocks_written;
5215 }
5216 if (num_ack_blocks_written >= num_ack_blocks) {
5217 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5218 QUIC_BUG << "Wrote " << num_ack_blocks_written
5219 << ", expected to write " << num_ack_blocks;
5220 }
5221 break;
5222 }
5223
5224 const uint8_t last_gap =
5225 total_gap -
5226 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5227 // Append the final ACK block with a non-empty size.
wub13d75452019-11-05 07:24:56 -08005228 if (!AppendAckBlock(last_gap, ack_block_length, interval.Length(),
5229 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005230 return false;
5231 }
5232 ++num_ack_blocks_written;
5233 }
5234 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5235 }
5236 // Timestamps.
5237 // If we don't process timestamps or if we don't have enough available space
5238 // to append all the timestamps, don't append any of them.
5239 if (process_timestamps_ && writer->capacity() - writer->length() >=
5240 GetAckFrameTimeStampSize(frame)) {
5241 if (!AppendTimestampsToAckFrame(frame, writer)) {
5242 return false;
5243 }
5244 } else {
5245 uint8_t num_received_packets = 0;
5246 if (!writer->WriteBytes(&num_received_packets, 1)) {
5247 return false;
5248 }
5249 }
5250
5251 return true;
5252}
5253
5254bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5255 QuicDataWriter* writer) {
5256 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5257 frame.received_packet_times.size());
5258 // num_received_packets is only 1 byte.
5259 if (frame.received_packet_times.size() >
5260 std::numeric_limits<uint8_t>::max()) {
5261 return false;
5262 }
5263
5264 uint8_t num_received_packets = frame.received_packet_times.size();
5265 if (!writer->WriteBytes(&num_received_packets, 1)) {
5266 return false;
5267 }
5268 if (num_received_packets == 0) {
5269 return true;
5270 }
5271
5272 auto it = frame.received_packet_times.begin();
5273 QuicPacketNumber packet_number = it->first;
5274 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5275
5276 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5277 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5278 return false;
5279 }
5280
5281 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5282 return false;
5283 }
5284
5285 // Use the lowest 4 bytes of the time delta from the creation_time_.
5286 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5287 uint32_t time_delta_us =
5288 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5289 (time_epoch_delta_us - 1));
5290 if (!writer->WriteUInt32(time_delta_us)) {
5291 return false;
5292 }
5293
5294 QuicTime prev_time = it->second;
5295
5296 for (++it; it != frame.received_packet_times.end(); ++it) {
5297 packet_number = it->first;
5298 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5299
5300 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5301 return false;
5302 }
5303
5304 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5305 return false;
5306 }
5307
5308 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5309 prev_time = it->second;
5310 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5311 return false;
5312 }
5313 }
5314 return true;
5315}
5316
5317bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5318 const QuicStopWaitingFrame& frame,
5319 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005320 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
bncbe885272020-01-16 11:10:48 -08005321 DCHECK(frame.least_unacked.IsInitialized());
5322 DCHECK_GE(header.packet_number, frame.least_unacked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005323 const uint64_t least_unacked_delta =
5324 header.packet_number - frame.least_unacked;
5325 const uint64_t length_shift = header.packet_number_length * 8;
5326
5327 if (least_unacked_delta >> length_shift > 0) {
5328 QUIC_BUG << "packet_number_length " << header.packet_number_length
5329 << " is too small for least_unacked_delta: " << least_unacked_delta
5330 << " packet_number:" << header.packet_number
5331 << " least_unacked:" << frame.least_unacked
5332 << " version:" << version_.transport_version;
5333 return false;
5334 }
5335 if (least_unacked_delta == 0) {
5336 return writer->WriteBytesToUInt64(header.packet_number_length,
5337 least_unacked_delta);
5338 }
5339 if (!AppendPacketNumber(header.packet_number_length,
5340 QuicPacketNumber(least_unacked_delta), writer)) {
5341 QUIC_BUG << " seq failed: " << header.packet_number_length;
5342 return false;
5343 }
5344
5345 return true;
5346}
5347
5348int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005349 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005350 size_t available_space) {
5351 // Number of blocks requested in the frame
5352 uint64_t ack_block_count = frame.packets.NumIntervals();
5353
5354 auto itr = frame.packets.rbegin();
5355
5356 int actual_block_count = 1;
5357 uint64_t block_length = itr->max() - itr->min();
5358 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5359 if (encoded_size > available_space) {
5360 return 0;
5361 }
5362 available_space -= encoded_size;
5363 QuicPacketNumber previous_ack_end = itr->min();
5364 ack_block_count--;
5365
5366 while (ack_block_count) {
5367 // Each block is a gap followed by another ACK. Calculate each value,
5368 // determine the encoded lengths, and check against the available space.
5369 itr++;
5370 size_t gap = previous_ack_end - itr->max() - 1;
5371 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5372
5373 // Add the ACK block.
5374 block_length = itr->max() - itr->min();
5375 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5376
5377 if (encoded_size > available_space) {
5378 // No room for this block, so what we've
5379 // done up to now is all that can be done.
5380 return actual_block_count;
5381 }
5382 available_space -= encoded_size;
5383 actual_block_count++;
5384 previous_ack_end = itr->min();
5385 ack_block_count--;
5386 }
5387 // Ran through the whole thing! We can do all blocks.
5388 return actual_block_count;
5389}
5390
5391bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5392 QuicDataWriter* writer) {
5393 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5394 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5395 uint8_t type = IETF_ACK;
5396 if (frame.ecn_counters_populated &&
5397 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5398 type = IETF_ACK_ECN;
5399 }
5400
5401 if (!writer->WriteUInt8(type)) {
5402 set_detailed_error("No room for frame-type");
5403 return false;
5404 }
5405
5406 QuicPacketNumber largest_acked = LargestAcked(frame);
5407 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5408 set_detailed_error("No room for largest-acked in ack frame");
5409 return false;
5410 }
5411
5412 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5413 if (!frame.ack_delay_time.IsInfinite()) {
5414 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5415 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005416 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005417 }
5418
5419 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5420 set_detailed_error("No room for ack-delay in ack frame");
5421 return false;
5422 }
5423 if (type == IETF_ACK_ECN) {
5424 // Encode the ACK ECN fields
5425 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5426 set_detailed_error("No room for ect_0_count in ack frame");
5427 return false;
5428 }
5429 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5430 set_detailed_error("No room for ect_1_count in ack frame");
5431 return false;
5432 }
5433 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5434 set_detailed_error("No room for ecn_ce_count in ack frame");
5435 return false;
5436 }
5437 }
5438
5439 uint64_t ack_block_count = frame.packets.NumIntervals();
5440 if (ack_block_count == 0) {
5441 // If the QuicAckFrame has no Intervals, then it is interpreted
5442 // as an ack of a single packet at QuicAckFrame.largest_acked.
5443 // The resulting ack will consist of only the frame's
5444 // largest_ack & first_ack_block fields. The first ack block will be 0
5445 // (indicating a single packet) and the ack block_count will be 0.
5446 if (!writer->WriteVarInt62(0)) {
5447 set_detailed_error("No room for ack block count in ack frame");
5448 return false;
5449 }
5450 // size of the first block is 1 packet
5451 if (!writer->WriteVarInt62(0)) {
5452 set_detailed_error("No room for first ack block in ack frame");
5453 return false;
5454 }
5455 return true;
5456 }
5457 // Case 2 or 3
5458 auto itr = frame.packets.rbegin();
5459
5460 QuicPacketNumber ack_block_largest(largest_acked);
5461 QuicPacketNumber ack_block_smallest;
5462 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5463 // If largest_acked + 1 is equal to the Max() of the first Interval
5464 // in the QuicAckFrame then the first Interval is the first ack block of the
5465 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5466 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5467 // the remaining Intervals are encoded in additional ack blocks in the
5468 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5469 // Intervals - 1.
5470 ack_block_smallest = itr->min();
5471 itr++;
5472 ack_block_count--;
5473 } else {
5474 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5475 // the first Interval then it is interpreted as acking a single
5476 // packet at QuicAckFrame.largest_acked, with additional
5477 // Intervals indicating additional ack blocks. The encoding is
5478 // a) The packet's largest_acked is the QuicAckFrame's largest
5479 // acked,
5480 // b) the first ack block size is 0,
5481 // c) The packet's ack_block_count is the number of QuicAckFrame
5482 // Intervals, and
5483 // d) The QuicAckFrame Intervals are encoded in additional ack
5484 // blocks in the packet.
5485 ack_block_smallest = largest_acked;
5486 }
5487
5488 if (!writer->WriteVarInt62(ack_block_count)) {
5489 set_detailed_error("No room for ack block count in ack frame");
5490 return false;
5491 }
5492
5493 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5494 if (!writer->WriteVarInt62(first_ack_block)) {
5495 set_detailed_error("No room for first ack block in ack frame");
5496 return false;
5497 }
5498
5499 // For the remaining QuicAckFrame Intervals, if any
5500 while (ack_block_count != 0) {
5501 uint64_t gap_size = ack_block_smallest - itr->max();
5502 if (!writer->WriteVarInt62(gap_size - 1)) {
5503 set_detailed_error("No room for gap block in ack frame");
5504 return false;
5505 }
5506
5507 uint64_t block_size = itr->max() - itr->min();
5508 if (!writer->WriteVarInt62(block_size - 1)) {
5509 set_detailed_error("No room for nth ack block in ack frame");
5510 return false;
5511 }
5512
5513 ack_block_smallest = itr->min();
5514 itr++;
5515 ack_block_count--;
5516 }
5517 return true;
5518}
5519
5520bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5521 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005522 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005523 return AppendIetfResetStreamFrame(frame, writer);
5524 }
5525 if (!writer->WriteUInt32(frame.stream_id)) {
5526 return false;
5527 }
5528
5529 if (!writer->WriteUInt64(frame.byte_offset)) {
5530 return false;
5531 }
5532
5533 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5534 if (!writer->WriteUInt32(error_code)) {
5535 return false;
5536 }
5537
5538 return true;
5539}
5540
5541bool QuicFramer::AppendConnectionCloseFrame(
5542 const QuicConnectionCloseFrame& 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 AppendIetfConnectionCloseFrame(frame, writer);
5546 }
fkastenholze9d71a82019-04-09 05:12:13 -07005547 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005548 if (!writer->WriteUInt32(error_code)) {
5549 return false;
5550 }
5551 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5552 return false;
5553 }
5554 return true;
5555}
5556
5557bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5558 QuicDataWriter* writer) {
5559 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5560 if (!writer->WriteUInt32(error_code)) {
5561 return false;
5562 }
5563 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5564 if (!writer->WriteUInt32(stream_id)) {
5565 return false;
5566 }
5567 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5568 return false;
5569 }
5570 return true;
5571}
5572
5573bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5574 QuicDataWriter* writer) {
5575 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5576 if (!writer->WriteUInt32(stream_id)) {
5577 return false;
5578 }
renjietangd088eab2019-11-21 14:54:41 -08005579 if (!writer->WriteUInt64(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005580 return false;
5581 }
5582 return true;
5583}
5584
5585bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5586 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005587 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005588 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5589 return AppendIetfBlockedFrame(frame, writer);
5590 }
5591 return AppendStreamBlockedFrame(frame, writer);
5592 }
5593 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5594 if (!writer->WriteUInt32(stream_id)) {
5595 return false;
5596 }
5597 return true;
5598}
5599
5600bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5601 QuicDataWriter* writer) {
5602 if (frame.num_padding_bytes == 0) {
5603 return false;
5604 }
5605 if (frame.num_padding_bytes < 0) {
5606 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5607 writer->WritePadding();
5608 return true;
5609 }
5610 // Please note, num_padding_bytes includes type byte which has been written.
5611 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5612}
5613
5614bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5615 bool last_frame_in_packet,
5616 QuicDataWriter* writer) {
dschinazicd86dd12019-11-14 10:11:13 -08005617 uint8_t type_byte;
5618 if (VersionHasIetfQuicFrames(version_.transport_version)) {
5619 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH_V99
5620 : IETF_EXTENSION_MESSAGE_V99;
5621 } else {
5622 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5623 : IETF_EXTENSION_MESSAGE;
5624 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005625 if (!writer->WriteUInt8(type_byte)) {
5626 return false;
5627 }
5628 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5629 return false;
5630 }
5631 for (const auto& slice : frame.message_data) {
5632 if (!writer->WriteBytes(slice.data(), slice.length())) {
5633 return false;
5634 }
5635 }
5636 return true;
5637}
5638
5639bool QuicFramer::RaiseError(QuicErrorCode error) {
5640 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5641 << " detail: " << detailed_error_;
5642 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005643 if (visitor_) {
5644 visitor_->OnError(this);
5645 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005646 return false;
5647}
5648
5649bool QuicFramer::IsVersionNegotiation(
5650 const QuicPacketHeader& header,
5651 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005652 if (!packet_has_ietf_packet_header &&
5653 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005654 return header.version_flag;
5655 }
5656 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5657 return false;
5658 }
5659 return header.long_packet_type == VERSION_NEGOTIATION;
5660}
5661
QUICHE teama6ef0a62019-03-07 20:34:33 -05005662bool QuicFramer::AppendIetfConnectionCloseFrame(
5663 const QuicConnectionCloseFrame& frame,
5664 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005665 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5666 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5667 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5668 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5669 return false;
5670 }
5671
fkastenholz88d08f42019-09-06 07:38:04 -07005672 if (!writer->WriteVarInt62(
5673 (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
5674 ? frame.transport_error_code
5675 : frame.application_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005676 set_detailed_error("Can not write connection close frame error code");
5677 return false;
5678 }
fkastenholze9d71a82019-04-09 05:12:13 -07005679
fkastenholz72f509b2019-04-10 09:17:49 -07005680 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5681 // Write the frame-type of the frame causing the error only
5682 // if it's a CONNECTION_CLOSE/Transport.
5683 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5684 set_detailed_error("Writing frame type failed.");
5685 return false;
5686 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005687 }
5688
fkastenholzb4dade72019-08-05 06:54:20 -07005689 // There may be additional error information available in the extracted error
5690 // code. Encode the error information in the reason phrase and serialize the
5691 // result.
5692 std::string final_error_string =
5693 GenerateErrorString(frame.error_details, frame.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005694 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005695 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005696 set_detailed_error("Can not write connection close phrase");
5697 return false;
5698 }
5699 return true;
5700}
5701
QUICHE teama6ef0a62019-03-07 20:34:33 -05005702bool QuicFramer::ProcessIetfConnectionCloseFrame(
5703 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005704 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005705 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005706 frame->close_type = type;
fkastenholzb4dade72019-08-05 06:54:20 -07005707
fkastenholz88d08f42019-09-06 07:38:04 -07005708 uint64_t error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005709 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005710 set_detailed_error("Unable to read connection close error code.");
5711 return false;
5712 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005713
fkastenholzd57d3f92019-07-16 09:05:17 -07005714 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005715 frame->transport_error_code =
5716 static_cast<QuicIetfTransportErrorCodes>(error_code);
fkastenholzd57d3f92019-07-16 09:05:17 -07005717 } else if (frame->close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005718 frame->application_error_code = error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005719 }
fkastenholzb4dade72019-08-05 06:54:20 -07005720
fkastenholz72f509b2019-04-10 09:17:49 -07005721 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5722 // The frame-type of the frame causing the error is present only
5723 // if it's a CONNECTION_CLOSE/Transport.
5724 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5725 set_detailed_error("Unable to read connection close frame type.");
5726 return false;
5727 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005728 }
5729
5730 uint64_t phrase_length;
5731 if (!reader->ReadVarInt62(&phrase_length)) {
5732 set_detailed_error("Unable to read connection close error details.");
5733 return false;
5734 }
fkastenholzb4dade72019-08-05 06:54:20 -07005735
dmcardlecf0bfcf2019-12-13 08:08:21 -08005736 quiche::QuicheStringPiece phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005737 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5738 set_detailed_error("Unable to read connection close error details.");
5739 return false;
5740 }
vasilvvc48c8712019-03-11 13:38:16 -07005741 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005742
fkastenholzb4dade72019-08-05 06:54:20 -07005743 // The frame may have an extracted error code in it. Look for it and
5744 // extract it. If it's not present, MaybeExtract will return
5745 // QUIC_IETF_GQUIC_ERROR_MISSING.
fkastenholz488a4622019-08-26 06:24:46 -07005746 MaybeExtractQuicErrorCode(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005747 return true;
5748}
5749
5750// IETF Quic Path Challenge/Response frames.
5751bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5752 QuicPathChallengeFrame* frame) {
5753 if (!reader->ReadBytes(frame->data_buffer.data(),
5754 frame->data_buffer.size())) {
5755 set_detailed_error("Can not read path challenge data.");
5756 return false;
5757 }
5758 return true;
5759}
5760
5761bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5762 QuicPathResponseFrame* frame) {
5763 if (!reader->ReadBytes(frame->data_buffer.data(),
5764 frame->data_buffer.size())) {
5765 set_detailed_error("Can not read path response data.");
5766 return false;
5767 }
5768 return true;
5769}
5770
5771bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5772 QuicDataWriter* writer) {
5773 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5774 set_detailed_error("Writing Path Challenge data failed.");
5775 return false;
5776 }
5777 return true;
5778}
5779
5780bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5781 QuicDataWriter* writer) {
5782 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5783 set_detailed_error("Writing Path Response data failed.");
5784 return false;
5785 }
5786 return true;
5787}
5788
5789// Add a new ietf-format stream reset frame.
5790// General format is
5791// stream id
5792// application error code
5793// final offset
5794bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5795 QuicDataWriter* writer) {
5796 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5797 set_detailed_error("Writing reset-stream stream id failed.");
5798 return false;
5799 }
fkastenholz07300e52019-07-16 11:51:37 -07005800 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005801 set_detailed_error("Writing reset-stream error code failed.");
5802 return false;
5803 }
5804 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5805 set_detailed_error("Writing reset-stream final-offset failed.");
5806 return false;
5807 }
5808 return true;
5809}
5810
5811bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5812 QuicRstStreamFrame* frame) {
5813 // Get Stream ID from frame. ReadVarIntStreamID returns false
5814 // if either A) there is a read error or B) the resulting value of
5815 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005816 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005817 set_detailed_error("Unable to read rst stream stream id.");
5818 return false;
5819 }
5820
fkastenholz07300e52019-07-16 11:51:37 -07005821 uint64_t error_code;
5822 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005823 set_detailed_error("Unable to read rst stream error code.");
5824 return false;
5825 }
fkastenholz07300e52019-07-16 11:51:37 -07005826 if (error_code > 0xffff) {
5827 frame->ietf_error_code = 0xffff;
5828 QUIC_DLOG(ERROR) << "Reset stream error code (" << error_code
5829 << ") > 0xffff";
5830 } else {
5831 frame->ietf_error_code = static_cast<uint16_t>(error_code);
5832 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005833
5834 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5835 set_detailed_error("Unable to read rst stream sent byte offset.");
5836 return false;
5837 }
5838 return true;
5839}
5840
5841bool QuicFramer::ProcessStopSendingFrame(
5842 QuicDataReader* reader,
5843 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005844 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005845 set_detailed_error("Unable to read stop sending stream id.");
5846 return false;
5847 }
5848
fkastenholz733552e2019-07-16 11:16:58 -07005849 uint64_t error_code;
5850 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005851 set_detailed_error("Unable to read stop sending application error code.");
5852 return false;
5853 }
fkastenholz733552e2019-07-16 11:16:58 -07005854 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5855 if (error_code > 0xffff) {
5856 stop_sending_frame->application_error_code = 0xffff;
5857 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5858 << ") > 0xffff";
5859 } else {
5860 stop_sending_frame->application_error_code =
5861 static_cast<uint16_t>(error_code);
5862 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005863 return true;
5864}
5865
5866bool QuicFramer::AppendStopSendingFrame(
5867 const QuicStopSendingFrame& stop_sending_frame,
5868 QuicDataWriter* writer) {
5869 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5870 set_detailed_error("Can not write stop sending stream id");
5871 return false;
5872 }
fkastenholz733552e2019-07-16 11:16:58 -07005873 if (!writer->WriteVarInt62(
5874 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005875 set_detailed_error("Can not write application error code");
5876 return false;
5877 }
5878 return true;
5879}
5880
5881// Append/process IETF-Format MAX_DATA Frame
5882bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5883 QuicDataWriter* writer) {
renjietangd088eab2019-11-21 14:54:41 -08005884 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005885 set_detailed_error("Can not write MAX_DATA byte-offset");
5886 return false;
5887 }
5888 return true;
5889}
5890
5891bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5892 QuicWindowUpdateFrame* frame) {
5893 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
renjietangd088eab2019-11-21 14:54:41 -08005894 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005895 set_detailed_error("Can not read MAX_DATA byte-offset");
5896 return false;
5897 }
5898 return true;
5899}
5900
5901// Append/process IETF-Format MAX_STREAM_DATA Frame
5902bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5903 QuicDataWriter* writer) {
5904 if (!writer->WriteVarInt62(frame.stream_id)) {
5905 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5906 return false;
5907 }
renjietangd088eab2019-11-21 14:54:41 -08005908 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005909 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5910 return false;
5911 }
5912 return true;
5913}
5914
5915bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5916 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005917 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005918 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5919 return false;
5920 }
renjietangd088eab2019-11-21 14:54:41 -08005921 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005922 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5923 return false;
5924 }
5925 return true;
5926}
5927
fkastenholz3c4eabf2019-04-22 07:49:59 -07005928bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005929 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005930 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005931 set_detailed_error("Can not write MAX_STREAMS stream count");
5932 return false;
5933 }
5934 return true;
5935}
5936
5937bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005938 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005939 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005940 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005941 set_detailed_error("Can not read MAX_STREAMS stream count.");
5942 return false;
5943 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005944 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
5945 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005946}
5947
5948bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
5949 QuicDataWriter* writer) {
5950 if (!writer->WriteVarInt62(frame.offset)) {
5951 set_detailed_error("Can not write blocked offset.");
5952 return false;
5953 }
5954 return true;
5955}
5956
5957bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
5958 QuicBlockedFrame* frame) {
5959 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
5960 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5961 if (!reader->ReadVarInt62(&frame->offset)) {
5962 set_detailed_error("Can not read blocked offset.");
5963 return false;
5964 }
5965 return true;
5966}
5967
5968bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
5969 QuicDataWriter* writer) {
5970 if (!writer->WriteVarInt62(frame.stream_id)) {
5971 set_detailed_error("Can not write stream blocked stream id.");
5972 return false;
5973 }
5974 if (!writer->WriteVarInt62(frame.offset)) {
5975 set_detailed_error("Can not write stream blocked offset.");
5976 return false;
5977 }
5978 return true;
5979}
5980
5981bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
5982 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005983 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005984 set_detailed_error("Can not read stream blocked stream id.");
5985 return false;
5986 }
5987 if (!reader->ReadVarInt62(&frame->offset)) {
5988 set_detailed_error("Can not read stream blocked offset.");
5989 return false;
5990 }
5991 return true;
5992}
5993
fkastenholz3c4eabf2019-04-22 07:49:59 -07005994bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
5995 QuicDataWriter* writer) {
5996 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005997 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
5998 return false;
5999 }
6000 return true;
6001}
6002
6003bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006004 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006005 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006006 if (!reader->ReadVarIntU32(&frame->stream_count)) {
6007 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006008 return false;
6009 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006010 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
fkastenholz3c4eabf2019-04-22 07:49:59 -07006011 if (frame->stream_count >
6012 QuicUtils::GetMaxStreamCount(
6013 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
6014 ((perspective_ == Perspective::IS_CLIENT)
6015 ? Perspective::IS_SERVER
6016 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006017 // If stream count is such that the resulting stream ID would exceed our
6018 // implementation limit, generate an error.
6019 set_detailed_error(
6020 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6021 return false;
6022 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006023 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006024}
6025
6026bool QuicFramer::AppendNewConnectionIdFrame(
6027 const QuicNewConnectionIdFrame& frame,
6028 QuicDataWriter* writer) {
6029 if (!writer->WriteVarInt62(frame.sequence_number)) {
6030 set_detailed_error("Can not write New Connection ID sequence number");
6031 return false;
6032 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006033 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6034 set_detailed_error("Can not write New Connection ID retire_prior_to");
6035 return false;
6036 }
dschinazicf5b1e22019-07-17 18:35:17 -07006037 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006038 set_detailed_error("Can not write New Connection ID frame connection ID");
6039 return false;
6040 }
6041
6042 if (!writer->WriteBytes(
6043 static_cast<const void*>(&frame.stateless_reset_token),
6044 sizeof(frame.stateless_reset_token))) {
6045 set_detailed_error("Can not write New Connection ID Reset Token");
6046 return false;
6047 }
6048 return true;
6049}
6050
6051bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6052 QuicNewConnectionIdFrame* frame) {
6053 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6054 set_detailed_error(
6055 "Unable to read new connection ID frame sequence number.");
6056 return false;
6057 }
6058
fkastenholz1c19fc22019-07-12 11:06:19 -07006059 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6060 set_detailed_error(
6061 "Unable to read new connection ID frame retire_prior_to.");
6062 return false;
6063 }
6064 if (frame->retire_prior_to > frame->sequence_number) {
6065 set_detailed_error("Retire_prior_to > sequence_number.");
6066 return false;
6067 }
dschinazicf5b1e22019-07-17 18:35:17 -07006068
6069 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6070 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006071 return false;
6072 }
6073
dschinazicf5b1e22019-07-17 18:35:17 -07006074 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6075 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006076 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006077 return false;
6078 }
6079
QUICHE teama6ef0a62019-03-07 20:34:33 -05006080 if (!reader->ReadBytes(&frame->stateless_reset_token,
6081 sizeof(frame->stateless_reset_token))) {
6082 set_detailed_error("Can not read new connection ID frame reset token.");
6083 return false;
6084 }
6085 return true;
6086}
6087
6088bool QuicFramer::AppendRetireConnectionIdFrame(
6089 const QuicRetireConnectionIdFrame& frame,
6090 QuicDataWriter* writer) {
6091 if (!writer->WriteVarInt62(frame.sequence_number)) {
6092 set_detailed_error("Can not write Retire Connection ID sequence number");
6093 return false;
6094 }
6095 return true;
6096}
6097
6098bool QuicFramer::ProcessRetireConnectionIdFrame(
6099 QuicDataReader* reader,
6100 QuicRetireConnectionIdFrame* frame) {
6101 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6102 set_detailed_error(
6103 "Unable to read retire connection ID frame sequence number.");
6104 return false;
6105 }
6106 return true;
6107}
6108
6109uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6110 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006111 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006112 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6113 }
6114 uint8_t type_byte = 0;
6115 // Fin bit.
6116 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6117
6118 // Data Length bit.
6119 type_byte <<= kQuicStreamDataLengthShift;
6120 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6121
6122 // Offset 3 bits.
6123 type_byte <<= kQuicStreamShift;
renjietang488201d2019-12-17 13:40:49 -08006124 const size_t offset_len = GetStreamOffsetSize(frame.offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006125 if (offset_len > 0) {
6126 type_byte |= offset_len - 1;
6127 }
6128
6129 // stream id 2 bits.
6130 type_byte <<= kQuicStreamIdShift;
6131 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6132 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6133
6134 return type_byte;
6135}
6136
6137uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6138 const QuicStreamFrame& frame,
6139 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006140 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006141 uint8_t type_byte = IETF_STREAM;
6142 if (!last_frame_in_packet) {
6143 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6144 }
6145 if (frame.offset != 0) {
6146 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6147 }
6148 if (frame.fin) {
6149 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6150 }
6151 return type_byte;
6152}
6153
6154void QuicFramer::InferPacketHeaderTypeFromVersion() {
6155 // This function should only be called when server connection negotiates the
6156 // version.
bncbe885272020-01-16 11:10:48 -08006157 DCHECK_EQ(perspective_, Perspective::IS_SERVER);
6158 DCHECK(!infer_packet_header_type_from_version_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006159 infer_packet_header_type_from_version_ = true;
6160}
6161
QUICHE team10b22a12019-03-21 15:31:42 -07006162void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6163 if (supports_multiple_packet_number_spaces_) {
6164 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6165 return;
6166 }
6167 if (largest_packet_number_.IsInitialized()) {
6168 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6169 "packet has been received.";
6170 return;
6171 }
6172
6173 supports_multiple_packet_number_spaces_ = true;
6174}
6175
fayangccbab732019-05-13 10:11:25 -07006176// static
dschinazi48ac9192019-07-31 00:07:26 -07006177QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6178 const QuicEncryptedPacket& packet,
6179 uint8_t expected_destination_connection_id_length,
6180 PacketHeaderFormat* format,
fayange3f2f7b2019-09-19 17:01:57 -07006181 QuicLongHeaderType* long_packet_type,
dschinazi48ac9192019-07-31 00:07:26 -07006182 bool* version_present,
6183 bool* has_length_prefix,
6184 QuicVersionLabel* version_label,
6185 ParsedQuicVersion* parsed_version,
6186 QuicConnectionId* destination_connection_id,
6187 QuicConnectionId* source_connection_id,
6188 bool* retry_token_present,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006189 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006190 std::string* detailed_error) {
6191 QuicDataReader reader(packet.data(), packet.length());
6192 if (reader.IsDoneReading()) {
6193 *detailed_error = "Unable to read first byte.";
6194 return QUIC_INVALID_PACKET_HEADER;
6195 }
6196 const uint8_t first_byte = reader.PeekByte();
6197 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6198 uint8_t unused_first_byte;
6199 QuicVariableLengthIntegerLength retry_token_length_length;
fayange3f2f7b2019-09-19 17:01:57 -07006200 QuicErrorCode error_code = ParsePublicHeader(
dschinazi48ac9192019-07-31 00:07:26 -07006201 &reader, expected_destination_connection_id_length, ietf_format,
6202 &unused_first_byte, format, version_present, has_length_prefix,
6203 version_label, parsed_version, destination_connection_id,
fayange3f2f7b2019-09-19 17:01:57 -07006204 source_connection_id, long_packet_type, &retry_token_length_length,
dschinazi48ac9192019-07-31 00:07:26 -07006205 retry_token, detailed_error);
6206 *retry_token_present =
6207 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6208 return error_code;
6209}
6210
6211// static
6212QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6213 QuicDataReader* reader,
6214 uint8_t* first_byte,
6215 PacketHeaderFormat* format,
6216 bool* version_present,
6217 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006218 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006219 QuicConnectionId* destination_connection_id,
6220 std::string* detailed_error) {
6221 *format = GOOGLE_QUIC_PACKET;
6222 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6223 uint8_t destination_connection_id_length = 0;
6224 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6225 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6226 }
6227 if (!reader->ReadConnectionId(destination_connection_id,
6228 destination_connection_id_length)) {
6229 *detailed_error = "Unable to read ConnectionId.";
6230 return QUIC_INVALID_PACKET_HEADER;
6231 }
dschinazi243eabc2019-08-05 16:15:29 -07006232 if (*version_present) {
6233 if (!ProcessVersionLabel(reader, version_label)) {
6234 *detailed_error = "Unable to read protocol version.";
6235 return QUIC_INVALID_PACKET_HEADER;
6236 }
6237 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006238 }
6239 return QUIC_NO_ERROR;
6240}
6241
6242namespace {
6243
dschinazi81eb4e02019-09-27 17:12:17 -07006244const QuicVersionLabel kProxVersionLabel = 0x50524F58; // "PROX"
6245
dschinazi48ac9192019-07-31 00:07:26 -07006246inline bool PacketHasLengthPrefixedConnectionIds(
6247 const QuicDataReader& reader,
6248 ParsedQuicVersion parsed_version,
6249 QuicVersionLabel version_label,
6250 uint8_t first_byte) {
6251 if (parsed_version.transport_version != QUIC_VERSION_UNSUPPORTED) {
6252 return parsed_version.HasLengthPrefixedConnectionIds();
6253 }
6254
6255 // Received unsupported version, check known old unsupported versions.
6256 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6257 return false;
6258 }
6259
6260 // Received unknown version, check connection ID length byte.
6261 if (reader.IsDoneReading()) {
6262 // This check is required to safely peek the connection ID length byte.
6263 return true;
6264 }
6265 const uint8_t connection_id_length_byte = reader.PeekByte();
6266
6267 // Check for packets produced by older versions of
6268 // QuicFramer::WriteClientVersionNegotiationProbePacket
6269 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6270 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6271 return false;
6272 }
6273
6274 // Check for munged packets with version tag PROX.
6275 if ((connection_id_length_byte & 0x0f) == 0 &&
dschinazi81eb4e02019-09-27 17:12:17 -07006276 connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) {
dschinazi48ac9192019-07-31 00:07:26 -07006277 return false;
6278 }
6279
6280 return true;
6281}
6282
6283inline bool ParseLongHeaderConnectionIds(
6284 QuicDataReader* reader,
6285 bool has_length_prefix,
dschinazi81eb4e02019-09-27 17:12:17 -07006286 QuicVersionLabel version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006287 QuicConnectionId* destination_connection_id,
6288 QuicConnectionId* source_connection_id,
6289 std::string* detailed_error) {
6290 if (has_length_prefix) {
6291 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6292 *detailed_error = "Unable to read destination connection ID.";
6293 return false;
6294 }
6295 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
dschinazi68fad8e2019-11-04 10:07:21 -08006296 if (version_label == kProxVersionLabel) {
dschinazi81eb4e02019-09-27 17:12:17 -07006297 // The "PROX" version does not follow the length-prefixed invariants,
6298 // and can therefore attempt to read a payload byte and interpret it
6299 // as the source connection ID length, which could fail to parse.
6300 // In that scenario we keep the source connection ID empty but mark
6301 // parsing as successful.
6302 return true;
6303 }
dschinazi48ac9192019-07-31 00:07:26 -07006304 *detailed_error = "Unable to read source connection ID.";
6305 return false;
6306 }
6307 } else {
6308 // Parse connection ID lengths.
6309 uint8_t connection_id_lengths_byte;
6310 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6311 *detailed_error = "Unable to read connection ID lengths.";
6312 return false;
6313 }
6314 uint8_t destination_connection_id_length =
6315 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6316 if (destination_connection_id_length != 0) {
6317 destination_connection_id_length += kConnectionIdLengthAdjustment;
6318 }
6319 uint8_t source_connection_id_length =
6320 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6321 if (source_connection_id_length != 0) {
6322 source_connection_id_length += kConnectionIdLengthAdjustment;
6323 }
6324
6325 // Read destination connection ID.
6326 if (!reader->ReadConnectionId(destination_connection_id,
6327 destination_connection_id_length)) {
6328 *detailed_error = "Unable to read destination connection ID.";
6329 return false;
6330 }
6331
6332 // Read source connection ID.
6333 if (!reader->ReadConnectionId(source_connection_id,
6334 source_connection_id_length)) {
6335 *detailed_error = "Unable to read source connection ID.";
6336 return false;
6337 }
6338 }
6339 return true;
6340}
6341
6342} // namespace
6343
6344// static
6345QuicErrorCode QuicFramer::ParsePublicHeader(
6346 QuicDataReader* reader,
6347 uint8_t expected_destination_connection_id_length,
6348 bool ietf_format,
6349 uint8_t* first_byte,
6350 PacketHeaderFormat* format,
6351 bool* version_present,
6352 bool* has_length_prefix,
6353 QuicVersionLabel* version_label,
6354 ParsedQuicVersion* parsed_version,
6355 QuicConnectionId* destination_connection_id,
6356 QuicConnectionId* source_connection_id,
6357 QuicLongHeaderType* long_packet_type,
6358 QuicVariableLengthIntegerLength* retry_token_length_length,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006359 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006360 std::string* detailed_error) {
6361 *version_present = false;
6362 *has_length_prefix = false;
6363 *version_label = 0;
6364 *parsed_version = UnsupportedQuicVersion();
6365 *source_connection_id = EmptyQuicConnectionId();
6366 *long_packet_type = INVALID_PACKET_TYPE;
6367 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006368 *retry_token = quiche::QuicheStringPiece();
dschinazi48ac9192019-07-31 00:07:26 -07006369 *detailed_error = "";
6370
6371 if (!reader->ReadUInt8(first_byte)) {
6372 *detailed_error = "Unable to read first byte.";
6373 return QUIC_INVALID_PACKET_HEADER;
6374 }
6375
6376 if (!ietf_format) {
6377 return ParsePublicHeaderGoogleQuic(
6378 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006379 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006380 }
6381
6382 *format = GetIetfPacketHeaderFormat(*first_byte);
6383
6384 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6385 // Read destination connection ID using
6386 // expected_destination_connection_id_length to determine its length.
6387 if (!reader->ReadConnectionId(destination_connection_id,
6388 expected_destination_connection_id_length)) {
6389 *detailed_error = "Unable to read destination connection ID.";
6390 return QUIC_INVALID_PACKET_HEADER;
6391 }
6392 return QUIC_NO_ERROR;
6393 }
6394
6395 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6396 *version_present = true;
6397 if (!ProcessVersionLabel(reader, version_label)) {
6398 *detailed_error = "Unable to read protocol version.";
6399 return QUIC_INVALID_PACKET_HEADER;
6400 }
6401
6402 if (*version_label == 0) {
6403 *long_packet_type = VERSION_NEGOTIATION;
6404 }
6405
6406 // Parse version.
6407 *parsed_version = ParseQuicVersionLabel(*version_label);
6408
6409 // Figure out which IETF QUIC invariants this packet follows.
6410 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6411 *reader, *parsed_version, *version_label, *first_byte);
6412
6413 // Parse connection IDs.
dschinazi81eb4e02019-09-27 17:12:17 -07006414 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix, *version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006415 destination_connection_id,
6416 source_connection_id, detailed_error)) {
6417 return QUIC_INVALID_PACKET_HEADER;
6418 }
6419
6420 if (parsed_version->transport_version == QUIC_VERSION_UNSUPPORTED) {
6421 // Skip parsing of long packet type and retry token for unknown versions.
6422 return QUIC_NO_ERROR;
6423 }
6424
6425 // Parse long packet type.
fayang36825da2019-08-21 14:01:27 -07006426 if (!GetLongHeaderType(*first_byte, long_packet_type)) {
dschinazi48ac9192019-07-31 00:07:26 -07006427 *detailed_error = "Unable to parse long packet type.";
6428 return QUIC_INVALID_PACKET_HEADER;
6429 }
6430
6431 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6432 // Retry token is only present on initial packets for some versions.
6433 return QUIC_NO_ERROR;
6434 }
6435
6436 *retry_token_length_length = reader->PeekVarInt62Length();
6437 uint64_t retry_token_length;
6438 if (!reader->ReadVarInt62(&retry_token_length)) {
6439 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6440 *detailed_error = "Unable to read retry token length.";
6441 return QUIC_INVALID_PACKET_HEADER;
6442 }
6443
6444 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6445 *detailed_error = "Unable to read retry token.";
6446 return QUIC_INVALID_PACKET_HEADER;
6447 }
6448
6449 return QUIC_NO_ERROR;
6450}
6451
6452// static
dschinazide0f6dc2019-05-15 16:10:11 -07006453bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6454 char* packet_bytes,
6455 QuicByteCount packet_length,
6456 const char* destination_connection_id_bytes,
6457 uint8_t destination_connection_id_length) {
6458 if (packet_bytes == nullptr) {
6459 QUIC_BUG << "Invalid packet_bytes";
6460 return false;
6461 }
6462 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6463 packet_length > 65535) {
6464 QUIC_BUG << "Invalid packet_length";
6465 return false;
6466 }
dschinazib012d212019-08-01 18:07:26 -07006467 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006468 destination_connection_id_length <
6469 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006470 QUIC_BUG << "Invalid connection_id_length";
6471 return false;
6472 }
dschinazi48ac9192019-07-31 00:07:26 -07006473 const bool use_length_prefix =
6474 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6475 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006476 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006477 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006478 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6479 0xc0,
6480 // Version, part of the IETF space reserved for negotiation.
6481 // This intentionally differs from QuicVersionReservedForNegotiation()
6482 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006483 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006484 };
6485 // clang-format on
6486 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6487 QuicDataWriter writer(packet_length, packet_bytes);
6488 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6489 QUIC_BUG << "Failed to write packet start";
6490 return false;
6491 }
6492
6493 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6494 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006495 if (!AppendIetfConnectionIds(
6496 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6497 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006498 QUIC_BUG << "Failed to write connection IDs";
6499 return false;
6500 }
6501 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6502 // not parse with any known version. The zeroes make sure that packet numbers,
6503 // retry token lengths and payload lengths are parsed as zero, and if the
6504 // zeroes are treated as padding frames, 0xff is known to not parse as a
6505 // valid frame type.
6506 if (!writer.WriteUInt64(0) ||
6507 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6508 QUIC_BUG << "Failed to write 18 bytes";
6509 return false;
6510 }
6511 // Make sure the polite greeting below is padded to a 16-byte boundary to
6512 // make it easier to read in tcpdump.
6513 while (writer.length() % 16 != 0) {
6514 if (!writer.WriteUInt8(0)) {
6515 QUIC_BUG << "Failed to write padding byte";
6516 return false;
6517 }
6518 }
6519 // Add a polite greeting in case a human sees this in tcpdump.
6520 static const char polite_greeting[] =
6521 "This packet only exists to trigger IETF QUIC version negotiation. "
6522 "Please respond with a Version Negotiation packet indicating what "
6523 "versions you support. Thank you and have a nice day.";
6524 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6525 QUIC_BUG << "Failed to write polite greeting";
6526 return false;
6527 }
6528 // Fill the rest of the packet with zeroes.
6529 writer.WritePadding();
6530 DCHECK_EQ(0u, writer.remaining());
6531 return true;
6532}
6533
6534// static
6535bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6536 const char* packet_bytes,
6537 QuicByteCount packet_length,
6538 char* source_connection_id_bytes,
6539 uint8_t* source_connection_id_length_out,
6540 std::string* detailed_error) {
6541 if (detailed_error == nullptr) {
6542 QUIC_BUG << "Invalid error_details";
6543 return false;
6544 }
6545 *detailed_error = "";
6546 if (packet_bytes == nullptr) {
6547 *detailed_error = "Invalid packet_bytes";
6548 return false;
6549 }
6550 if (packet_length < 6) {
6551 *detailed_error = "Invalid packet_length";
6552 return false;
6553 }
6554 if (source_connection_id_bytes == nullptr) {
6555 *detailed_error = "Invalid source_connection_id_bytes";
6556 return false;
6557 }
6558 if (source_connection_id_length_out == nullptr) {
6559 *detailed_error = "Invalid source_connection_id_length_out";
6560 return false;
6561 }
6562 QuicDataReader reader(packet_bytes, packet_length);
6563 uint8_t type_byte = 0;
6564 if (!reader.ReadUInt8(&type_byte)) {
6565 *detailed_error = "Failed to read type byte";
6566 return false;
6567 }
6568 if ((type_byte & 0x80) == 0) {
6569 *detailed_error = "Packet does not have long header";
6570 return false;
6571 }
6572 uint32_t version = 0;
6573 if (!reader.ReadUInt32(&version)) {
6574 *detailed_error = "Failed to read version";
6575 return false;
6576 }
6577 if (version != 0) {
6578 *detailed_error = "Packet is not a version negotiation packet";
6579 return false;
6580 }
dschinazi48ac9192019-07-31 00:07:26 -07006581 const bool use_length_prefix =
6582 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006583 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006584 if (use_length_prefix) {
6585 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6586 *detailed_error = "Failed to read destination connection ID";
6587 return false;
6588 }
6589 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6590 *detailed_error = "Failed to read source connection ID";
6591 return false;
6592 }
6593 } else {
6594 uint8_t expected_server_connection_id_length = 0,
6595 destination_connection_id_length = 0,
6596 source_connection_id_length = 0;
6597 if (!ProcessAndValidateIetfConnectionIdLength(
6598 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6599 /*should_update_expected_server_connection_id_length=*/true,
6600 &expected_server_connection_id_length,
6601 &destination_connection_id_length, &source_connection_id_length,
6602 detailed_error)) {
6603 return false;
6604 }
6605 if (!reader.ReadConnectionId(&destination_connection_id,
6606 destination_connection_id_length)) {
6607 *detailed_error = "Failed to read destination connection ID";
6608 return false;
6609 }
6610 if (!reader.ReadConnectionId(&source_connection_id,
6611 source_connection_id_length)) {
6612 *detailed_error = "Failed to read source connection ID";
6613 return false;
6614 }
dschinazide0f6dc2019-05-15 16:10:11 -07006615 }
dschinazi48ac9192019-07-31 00:07:26 -07006616
6617 if (destination_connection_id.length() != 0) {
6618 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006619 return false;
6620 }
6621
6622 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006623 source_connection_id.length());
6624 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006625
6626 return true;
6627}
6628
fkastenholzb4dade72019-08-05 06:54:20 -07006629// Look for and parse the error code from the "<quic_error_code>:" text that
6630// may be present at the start of the CONNECTION_CLOSE error details string.
6631// This text, inserted by the peer if it's using Google's QUIC implementation,
6632// contains additional error information that narrows down the exact error. If
6633// the string is not found, or is not properly formed, it returns
6634// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
fkastenholz488a4622019-08-26 06:24:46 -07006635void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08006636 std::vector<quiche::QuicheStringPiece> ed =
6637 quiche::QuicheTextUtils::Split(frame->error_details, ':');
fkastenholzb4dade72019-08-05 06:54:20 -07006638 uint64_t extracted_error_code;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006639 if (ed.size() < 2 || !quiche::QuicheTextUtils::IsAllDigits(ed[0]) ||
6640 !quiche::QuicheTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
dschinazidce90b02019-10-14 18:19:54 -07006641 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
6642 frame->transport_error_code == NO_IETF_QUIC_ERROR) {
6643 frame->extracted_error_code = QUIC_NO_ERROR;
6644 } else {
6645 frame->extracted_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
6646 }
fkastenholz488a4622019-08-26 06:24:46 -07006647 return;
fkastenholzb4dade72019-08-05 06:54:20 -07006648 }
fkastenholz488a4622019-08-26 06:24:46 -07006649 // Return the error code (numeric) and the error details string without the
6650 // error code prefix. Note that Split returns everything up to, but not
6651 // including, the split character, so the length of ed[0] is just the number
6652 // of digits in the error number. In removing the prefix, 1 is added to the
6653 // length to account for the :
dmcardlecf0bfcf2019-12-13 08:08:21 -08006654 quiche::QuicheStringPiece x = quiche::QuicheStringPiece(frame->error_details);
fkastenholz488a4622019-08-26 06:24:46 -07006655 x.remove_prefix(ed[0].length() + 1);
6656 frame->error_details = std::string(x);
6657 frame->extracted_error_code =
6658 static_cast<QuicErrorCode>(extracted_error_code);
fkastenholzb4dade72019-08-05 06:54:20 -07006659}
6660
QUICHE teama6ef0a62019-03-07 20:34:33 -05006661#undef ENDPOINT // undef for jumbo builds
6662} // namespace quic