blob: cc10cca6ebb3cd18536507d866c1c6db72f2881f [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/quic_framer.h"
6
7#include <cstddef>
8#include <cstdint>
9#include <memory>
vasilvv872e7a32019-03-12 16:42:44 -070010#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050011
12#include "net/third_party/quiche/src/quic/core/crypto/crypto_framer.h"
13#include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake_message.h"
14#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
15#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
16#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
17#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
20#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
21#include "net/third_party/quiche/src/quic/core/quic_constants.h"
22#include "net/third_party/quiche/src/quic/core/quic_data_reader.h"
23#include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
24#include "net/third_party/quiche/src/quic/core/quic_socket_address_coder.h"
25#include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h"
26#include "net/third_party/quiche/src/quic/core/quic_types.h"
27#include "net/third_party/quiche/src/quic/core/quic_utils.h"
28#include "net/third_party/quiche/src/quic/core/quic_versions.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_aligned.h"
dschinazie8d7fa72019-04-05 14:44:40 -070030#include "net/third_party/quiche/src/quic/platform/api/quic_arraysize.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_client_stats.h"
33#include "net/third_party/quiche/src/quic/platform/api/quic_endian.h"
34#include "net/third_party/quiche/src/quic/platform/api/quic_fallthrough.h"
35#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
36#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
37#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
38#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
39#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
40#include "net/third_party/quiche/src/quic/platform/api/quic_stack_trace.h"
41#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050042#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
43
44namespace quic {
45
46namespace {
47
48#define ENDPOINT \
49 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
50
51// How much to shift the timestamp in the IETF Ack frame.
52// TODO(fkastenholz) when we get real IETF QUIC, need to get
53// the currect shift from the transport parameters.
54const int kIetfAckTimestampShift = 3;
55
56// Number of bits the packet number length bits are shifted from the right
57// edge of the header.
58const uint8_t kPublicHeaderSequenceNumberShift = 4;
59
60// There are two interpretations for the Frame Type byte in the QUIC protocol,
61// resulting in two Frame Types: Special Frame Types and Regular Frame Types.
62//
63// Regular Frame Types use the Frame Type byte simply. Currently defined
64// Regular Frame Types are:
65// Padding : 0b 00000000 (0x00)
66// ResetStream : 0b 00000001 (0x01)
67// ConnectionClose : 0b 00000010 (0x02)
68// GoAway : 0b 00000011 (0x03)
69// WindowUpdate : 0b 00000100 (0x04)
70// Blocked : 0b 00000101 (0x05)
71//
72// Special Frame Types encode both a Frame Type and corresponding flags
73// all in the Frame Type byte. Currently defined Special Frame Types
74// are:
75// Stream : 0b 1xxxxxxx
76// Ack : 0b 01xxxxxx
77//
78// Semantics of the flag bits above (the x bits) depends on the frame type.
79
80// Masks to determine if the frame type is a special use
81// and for specific special frame types.
82const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000
83const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000
84const uint8_t kQuicFrameTypeStreamMask = 0x80;
85const uint8_t kQuicFrameTypeAckMask = 0x40;
86static_assert(kQuicFrameTypeSpecialMask ==
87 (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask),
88 "Invalid kQuicFrameTypeSpecialMask");
89
90// The stream type format is 1FDOOOSS, where
91// F is the fin bit.
92// D is the data length bit (0 or 2 bytes).
93// OO/OOO are the size of the offset.
94// SS is the size of the stream ID.
95// Note that the stream encoding can not be determined by inspection. It can
96// be determined only by knowing the QUIC Version.
97// Stream frame relative shifts and masks for interpreting the stream flags.
98// StreamID may be 1, 2, 3, or 4 bytes.
99const uint8_t kQuicStreamIdShift = 2;
100const uint8_t kQuicStreamIDLengthMask = 0x03;
101
102// Offset may be 0, 2, 4, or 8 bytes.
103const uint8_t kQuicStreamShift = 3;
104const uint8_t kQuicStreamOffsetMask = 0x07;
105
106// Data length may be 0 or 2 bytes.
107const uint8_t kQuicStreamDataLengthShift = 1;
108const uint8_t kQuicStreamDataLengthMask = 0x01;
109
110// Fin bit may be set or not.
111const uint8_t kQuicStreamFinShift = 1;
112const uint8_t kQuicStreamFinMask = 0x01;
113
114// The format is 01M0LLOO, where
115// M if set, there are multiple ack blocks in the frame.
116// LL is the size of the largest ack field.
117// OO is the size of the ack blocks offset field.
118// packet number size shift used in AckFrames.
119const uint8_t kQuicSequenceNumberLengthNumBits = 2;
120const uint8_t kActBlockLengthOffset = 0;
121const uint8_t kLargestAckedOffset = 2;
122
123// Acks may have only one ack block.
124const uint8_t kQuicHasMultipleAckBlocksOffset = 5;
125
126// Timestamps are 4 bytes followed by 2 bytes.
127const uint8_t kQuicNumTimestampsLength = 1;
128const uint8_t kQuicFirstTimestampLength = 4;
129const uint8_t kQuicTimestampLength = 2;
130// Gaps between packet numbers are 1 byte.
131const uint8_t kQuicTimestampPacketNumberGapLength = 1;
132
133// Maximum length of encoded error strings.
134const int kMaxErrorStringLength = 256;
135
136const uint8_t kConnectionIdLengthAdjustment = 3;
137const uint8_t kDestinationConnectionIdLengthMask = 0xF0;
138const uint8_t kSourceConnectionIdLengthMask = 0x0F;
139
140// Returns the absolute value of the difference between |a| and |b|.
141uint64_t Delta(uint64_t a, uint64_t b) {
142 // Since these are unsigned numbers, we can't just return abs(a - b)
143 if (a < b) {
144 return b - a;
145 }
146 return a - b;
147}
148
149uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) {
150 return (Delta(target, a) < Delta(target, b)) ? a : b;
151}
152
153uint64_t PacketNumberIntervalLength(
154 const QuicInterval<QuicPacketNumber>& interval) {
155 if (interval.Empty()) {
156 return 0u;
157 }
158 return interval.max() - interval.min();
159}
160
161QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) {
162 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
163 case PACKET_FLAGS_8BYTE_PACKET:
164 return PACKET_6BYTE_PACKET_NUMBER;
165 case PACKET_FLAGS_4BYTE_PACKET:
166 return PACKET_4BYTE_PACKET_NUMBER;
167 case PACKET_FLAGS_2BYTE_PACKET:
168 return PACKET_2BYTE_PACKET_NUMBER;
169 case PACKET_FLAGS_1BYTE_PACKET:
170 return PACKET_1BYTE_PACKET_NUMBER;
171 default:
172 QUIC_BUG << "Unreachable case statement.";
173 return PACKET_6BYTE_PACKET_NUMBER;
174 }
175}
176
177QuicPacketNumberLength ReadAckPacketNumberLength(QuicTransportVersion version,
178 uint8_t flags) {
179 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
180 case PACKET_FLAGS_8BYTE_PACKET:
181 return PACKET_6BYTE_PACKET_NUMBER;
182 case PACKET_FLAGS_4BYTE_PACKET:
183 return PACKET_4BYTE_PACKET_NUMBER;
184 case PACKET_FLAGS_2BYTE_PACKET:
185 return PACKET_2BYTE_PACKET_NUMBER;
186 case PACKET_FLAGS_1BYTE_PACKET:
187 return PACKET_1BYTE_PACKET_NUMBER;
188 default:
189 QUIC_BUG << "Unreachable case statement.";
190 return PACKET_6BYTE_PACKET_NUMBER;
191 }
192}
193
194uint8_t PacketNumberLengthToOnWireValue(
195 QuicTransportVersion version,
196 QuicPacketNumberLength packet_number_length) {
197 if (version > QUIC_VERSION_44) {
198 return packet_number_length - 1;
199 }
200 switch (packet_number_length) {
201 case PACKET_1BYTE_PACKET_NUMBER:
202 return 0;
203 case PACKET_2BYTE_PACKET_NUMBER:
204 return 1;
205 case PACKET_4BYTE_PACKET_NUMBER:
206 return 2;
207 default:
208 QUIC_BUG << "Invalid packet number length.";
209 return 0;
210 }
211}
212
213bool GetShortHeaderPacketNumberLength(
214 QuicTransportVersion version,
215 uint8_t type,
216 bool infer_packet_header_type_from_version,
217 QuicPacketNumberLength* packet_number_length) {
218 DCHECK(!(type & FLAGS_LONG_HEADER));
219 const bool two_bits_packet_number_length =
220 infer_packet_header_type_from_version ? version > QUIC_VERSION_44
221 : (type & FLAGS_FIXED_BIT);
222 if (two_bits_packet_number_length) {
223 *packet_number_length =
224 static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
225 return true;
226 }
227 switch (type & 0x07) {
228 case 0:
229 *packet_number_length = PACKET_1BYTE_PACKET_NUMBER;
230 break;
231 case 1:
232 *packet_number_length = PACKET_2BYTE_PACKET_NUMBER;
233 break;
234 case 2:
235 *packet_number_length = PACKET_4BYTE_PACKET_NUMBER;
236 break;
237 default:
238 *packet_number_length = PACKET_6BYTE_PACKET_NUMBER;
239 return false;
240 }
241 return true;
242}
243
244uint8_t LongHeaderTypeToOnWireValue(QuicTransportVersion version,
245 QuicLongHeaderType type) {
246 switch (type) {
247 case INITIAL:
248 return version > QUIC_VERSION_44 ? 0 : 0x7F;
249 case ZERO_RTT_PROTECTED:
250 return version > QUIC_VERSION_44 ? 1 << 4 : 0x7C;
251 case HANDSHAKE:
252 return version > QUIC_VERSION_44 ? 2 << 4 : 0x7D;
253 case RETRY:
254 return version > QUIC_VERSION_44 ? 3 << 4 : 0x7E;
255 case VERSION_NEGOTIATION:
256 return 0xF0; // Value does not matter
257 default:
258 QUIC_BUG << "Invalid long header type: " << type;
259 return 0xFF;
260 }
261}
262
263bool GetLongHeaderType(QuicTransportVersion version,
264 uint8_t type,
265 QuicLongHeaderType* long_header_type) {
266 DCHECK((type & FLAGS_LONG_HEADER) && version != QUIC_VERSION_UNSUPPORTED);
267 if (version > QUIC_VERSION_44) {
268 switch ((type & 0x30) >> 4) {
269 case 0:
270 *long_header_type = INITIAL;
271 break;
272 case 1:
273 *long_header_type = ZERO_RTT_PROTECTED;
274 break;
275 case 2:
276 *long_header_type = HANDSHAKE;
277 break;
278 case 3:
279 *long_header_type = RETRY;
280 break;
281 default:
282 QUIC_BUG << "Unreachable statement";
283 *long_header_type = VERSION_NEGOTIATION;
284 return false;
285 }
286 return true;
287 }
288
289 switch (type & 0x7F) {
290 case 0x7F:
291 *long_header_type = INITIAL;
292 break;
293 case 0x7C:
294 *long_header_type = ZERO_RTT_PROTECTED;
295 break;
296 case 0x7D:
297 *long_header_type = HANDSHAKE;
298 break;
299 case 0x7E:
300 *long_header_type = RETRY;
301 break;
302 default:
303 // Invalid packet header type. Whether a packet is version negotiation is
304 // determined by the version field.
305 *long_header_type = INVALID_PACKET_TYPE;
306 return false;
307 }
308 return true;
309}
310
311QuicPacketNumberLength GetLongHeaderPacketNumberLength(
312 QuicTransportVersion version,
313 uint8_t type) {
314 if (version > QUIC_VERSION_44) {
315 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
316 }
317 return PACKET_4BYTE_PACKET_NUMBER;
318}
319
QUICHE team10b22a12019-03-21 15:31:42 -0700320// Used to get packet number space before packet gets decrypted.
321PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
322 switch (header.form) {
323 case GOOGLE_QUIC_PACKET:
324 QUIC_BUG << "Try to get packet number space of Google QUIC packet";
325 break;
326 case IETF_QUIC_SHORT_HEADER_PACKET:
327 return APPLICATION_DATA;
328 case IETF_QUIC_LONG_HEADER_PACKET:
329 switch (header.long_packet_type) {
330 case INITIAL:
331 return INITIAL_DATA;
332 case HANDSHAKE:
333 return HANDSHAKE_DATA;
334 case ZERO_RTT_PROTECTED:
335 return APPLICATION_DATA;
336 case VERSION_NEGOTIATION:
337 case RETRY:
338 case INVALID_PACKET_TYPE:
339 QUIC_BUG << "Try to get packet number space of long header type: "
340 << QuicUtils::QuicLongHeaderTypetoString(
341 header.long_packet_type);
342 break;
343 }
344 }
345
346 return NUM_PACKET_NUMBER_SPACES;
347}
348
zhongyi546cc452019-04-12 15:27:49 -0700349EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
350 switch (header.form) {
351 case GOOGLE_QUIC_PACKET:
352 QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header";
353 break;
354 case IETF_QUIC_SHORT_HEADER_PACKET:
355 return ENCRYPTION_FORWARD_SECURE;
356 case IETF_QUIC_LONG_HEADER_PACKET:
357 switch (header.long_packet_type) {
358 case INITIAL:
359 return ENCRYPTION_INITIAL;
360 case HANDSHAKE:
361 return ENCRYPTION_HANDSHAKE;
362 case ZERO_RTT_PROTECTED:
363 return ENCRYPTION_ZERO_RTT;
364 case VERSION_NEGOTIATION:
365 case RETRY:
366 case INVALID_PACKET_TYPE:
367 QUIC_BUG << "No encryption used with type "
368 << QuicUtils::QuicLongHeaderTypetoString(
369 header.long_packet_type);
370 }
371 }
372 return NUM_ENCRYPTION_LEVELS;
373}
374
QUICHE teama6ef0a62019-03-07 20:34:33 -0500375QuicStringPiece TruncateErrorString(QuicStringPiece error) {
376 if (error.length() <= kMaxErrorStringLength) {
377 return error;
378 }
379 return QuicStringPiece(error.data(), kMaxErrorStringLength);
380}
381
382size_t TruncatedErrorStringSize(const QuicStringPiece& error) {
383 if (error.length() < kMaxErrorStringLength) {
384 return error.length();
385 }
386 return kMaxErrorStringLength;
387}
388
389uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) {
390 if (length == 0) {
391 return 0;
392 }
393 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
394}
395
396bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
397 size_t length = packet_number_length;
398 return length == 1 || length == 2 || length == 4 || length == 6 ||
399 length == 8;
400}
401
402bool IsValidFullPacketNumber(uint64_t full_packet_number,
403 QuicTransportVersion version) {
QUICHE team577718a2019-03-20 09:00:59 -0700404 return full_packet_number > 0 || version == QUIC_VERSION_99;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500405}
406
407// Convert a stream ID to a count of streams, for IETF QUIC/Version 99 only.
408// There is no need to take into account whether the ID is for uni- or
409// bi-directional streams, or whether it's server- or client- initiated. It
410// always returns a valid count.
411QuicStreamId StreamIdToCount(QuicTransportVersion version,
412 QuicStreamId stream_id) {
413 DCHECK_EQ(QUIC_VERSION_99, version);
414 if ((stream_id & 0x3) == 0) {
415 return (stream_id / QuicUtils::StreamIdDelta(version));
416 }
417 return (stream_id / QuicUtils::StreamIdDelta(version)) + 1;
418}
419
420// Returns the maximum value that a stream count may have, taking into account
421// the fact that bidirectional, client initiated, streams have one fewer stream
422// available than the others. This is because the old crypto streams, with ID ==
423// 0 are not included in the count.
424// The version is not included in the call, nor does the method take the version
425// into account, because this is called only from code used for IETF QUIC.
426// TODO(fkastenholz): Remove this method and replace calls to it with direct
427// references to kMaxQuicStreamIdCount when streamid 0 becomes a normal stream
428// id.
429QuicStreamId GetMaxStreamCount(bool unidirectional, Perspective perspective) {
430 if (!unidirectional && perspective == Perspective::IS_CLIENT) {
431 return kMaxQuicStreamId >> 2;
432 }
433 return (kMaxQuicStreamId >> 2) + 1;
434}
435
436// Convert a stream count to the maximum stream ID for that count.
437// Needs to know whether the resulting stream ID should be uni-directional,
438// bi-directional, server-initiated, or client-initiated.
439// Returns true if it works, false if not. The only error condition is that
440// the stream_count is too big and it would generate a stream id that is larger
441// than the implementation's maximum stream id value.
442bool StreamCountToId(QuicStreamId stream_count,
443 bool unidirectional,
444 Perspective perspective,
445 QuicTransportVersion version,
446 QuicStreamId* generated_stream_id) {
447 DCHECK_EQ(QUIC_VERSION_99, version);
448 // TODO(fkastenholz): when the MAX_STREAMS and STREAMS_BLOCKED frames
449 // are connected all the way up to the stream_id_manager, handle count==0
450 // properly (interpret it as "can open 0 streams") and the count being too
451 // large (close the connection).
452 if ((stream_count == 0) ||
453 (stream_count > GetMaxStreamCount(unidirectional, perspective))) {
454 return false;
455 }
456 *generated_stream_id =
457 ((unidirectional)
458 ? QuicUtils::GetFirstUnidirectionalStreamId(version, perspective)
459 : QuicUtils::GetFirstBidirectionalStreamId(version, perspective)) +
460 ((stream_count - 1) * QuicUtils::StreamIdDelta(version));
461 return true;
462}
463
464bool AppendIetfConnectionIdsNew(bool version_flag,
465 QuicConnectionId destination_connection_id,
466 QuicConnectionId source_connection_id,
467 QuicDataWriter* writer) {
468 if (!version_flag) {
469 return writer->WriteConnectionId(destination_connection_id);
470 }
471
472 // Compute connection ID length byte.
473 uint8_t dcil = GetConnectionIdLengthValue(
474 static_cast<QuicConnectionIdLength>(destination_connection_id.length()));
475 uint8_t scil = GetConnectionIdLengthValue(
476 static_cast<QuicConnectionIdLength>(source_connection_id.length()));
477 uint8_t connection_id_length = dcil << 4 | scil;
478
479 return writer->WriteUInt8(connection_id_length) &&
480 writer->WriteConnectionId(destination_connection_id) &&
481 writer->WriteConnectionId(source_connection_id);
482}
483
484enum class DroppedPacketReason {
485 // General errors
486 INVALID_PUBLIC_HEADER,
487 VERSION_MISMATCH,
488 // Version negotiation packet errors
489 INVALID_VERSION_NEGOTIATION_PACKET,
490 // Public reset packet errors, pre-v44
491 INVALID_PUBLIC_RESET_PACKET,
492 // Data packet errors
493 INVALID_PACKET_NUMBER,
494 INVALID_DIVERSIFICATION_NONCE,
495 DECRYPTION_FAILURE,
496 NUM_REASONS,
497};
498
499void RecordDroppedPacketReason(DroppedPacketReason reason) {
500 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
501 DroppedPacketReason::NUM_REASONS,
502 "The reason a packet was not processed. Recorded "
503 "each time such a packet is dropped");
504}
505
506} // namespace
507
508QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
509 QuicTime creation_time,
510 Perspective perspective,
511 uint8_t expected_connection_id_length)
512 : visitor_(nullptr),
513 error_(QUIC_NO_ERROR),
514 last_serialized_connection_id_(EmptyQuicConnectionId()),
515 last_version_label_(0),
516 version_(PROTOCOL_UNSUPPORTED, QUIC_VERSION_UNSUPPORTED),
517 supported_versions_(supported_versions),
QUICHE team6987b4a2019-03-15 16:23:04 -0700518 decrypter_level_(ENCRYPTION_INITIAL),
QUICHE team76086e42019-03-25 15:12:29 -0700519 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500520 alternative_decrypter_latch_(false),
521 perspective_(perspective),
522 validate_flags_(true),
523 process_timestamps_(false),
524 creation_time_(creation_time),
525 last_timestamp_(QuicTime::Delta::Zero()),
526 first_sending_packet_number_(FirstSendingPacketNumber()),
527 data_producer_(nullptr),
528 infer_packet_header_type_from_version_(perspective ==
529 Perspective::IS_CLIENT),
QUICHE team4d9d6292019-03-11 14:25:33 -0700530 expected_connection_id_length_(expected_connection_id_length),
QUICHE team10b22a12019-03-21 15:31:42 -0700531 should_update_expected_connection_id_length_(false),
532 supports_multiple_packet_number_spaces_(false) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500533 DCHECK(!supported_versions.empty());
534 version_ = supported_versions_[0];
QUICHE team76086e42019-03-25 15:12:29 -0700535 decrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullDecrypter>(perspective);
QUICHE team6987b4a2019-03-15 16:23:04 -0700536 encrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullEncrypter>(perspective);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500537}
538
539QuicFramer::~QuicFramer() {}
540
541// static
542size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
543 QuicStreamId stream_id,
544 QuicStreamOffset offset,
545 bool last_frame_in_packet,
546 QuicPacketLength data_length) {
547 if (version == QUIC_VERSION_99) {
548 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
549 (last_frame_in_packet
550 ? 0
551 : QuicDataWriter::GetVarInt62Len(data_length)) +
552 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
553 }
554 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
555 GetStreamOffsetSize(version, offset) +
556 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
557}
558
559// static
560size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
561 QuicPacketLength data_length) {
562 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
563 QuicDataWriter::GetVarInt62Len(data_length);
564}
565
566// static
567size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
568 bool last_frame_in_packet,
569 QuicByteCount length) {
570 QUIC_BUG_IF(version <= QUIC_VERSION_44)
571 << "Try to serialize MESSAGE frame in " << version;
572 return kQuicFrameTypeSize +
573 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
574 length;
575}
576
577// static
578size_t QuicFramer::GetMinAckFrameSize(
579 QuicTransportVersion version,
580 QuicPacketNumberLength largest_observed_length) {
581 if (version == QUIC_VERSION_99) {
582 // The minimal ack frame consists of the following four fields: Largest
583 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
584 // size of each is 1 byte.
585 return kQuicFrameTypeSize + 4;
586 }
587 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
588 kQuicDeltaTimeLargestObservedSize;
589 return min_size + kQuicNumTimestampsSize;
590}
591
592// static
593size_t QuicFramer::GetStopWaitingFrameSize(
594 QuicTransportVersion version,
595 QuicPacketNumberLength packet_number_length) {
596 size_t min_size = kQuicFrameTypeSize + packet_number_length;
597 return min_size;
598}
599
600// static
601size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
602 const QuicRstStreamFrame& frame) {
603 if (version == QUIC_VERSION_99) {
604 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
605 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
606 kQuicFrameTypeSize + kQuicIetfQuicErrorCodeSize;
607 }
608 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
609 kQuicErrorCodeSize;
610}
611
612// static
613size_t QuicFramer::GetMinConnectionCloseFrameSize(
614 QuicTransportVersion version,
615 const QuicConnectionCloseFrame& frame) {
616 if (version == QUIC_VERSION_99) {
fkastenholz72f509b2019-04-10 09:17:49 -0700617 // TODO(fkastenholz): For complete support of IETF QUIC CONNECTION_CLOSE,
618 // check if the frame is a Transport close and if the frame's
619 // extracted_error_code is not QUIC_IETF_GQUIC_ERROR_MISSING. If so,
620 // extend the error string to include " QuicErrorCode: #"
621 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
622 // Application close variant does not include the transport close frame
623 // type field.
624 return QuicDataWriter::GetVarInt62Len(
625 TruncatedErrorStringSize(frame.error_details)) +
626 kQuicFrameTypeSize + kQuicIetfQuicErrorCodeSize;
627 }
628 QUIC_BUG_IF(frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
629 << "IETF QUIC Connection close and QuicConnectionCloseFrame type is "
630 "not IETF ConnectionClose";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500631 return QuicDataWriter::GetVarInt62Len(
632 TruncatedErrorStringSize(frame.error_details)) +
fkastenholze9d71a82019-04-09 05:12:13 -0700633 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500634 kQuicFrameTypeSize + kQuicIetfQuicErrorCodeSize;
635 }
fkastenholz72f509b2019-04-10 09:17:49 -0700636 // Not version 99/IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500637 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize;
638}
639
640// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500641size_t QuicFramer::GetMinGoAwayFrameSize() {
642 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
643 kQuicMaxStreamIdSize;
644}
645
646// static
647size_t QuicFramer::GetWindowUpdateFrameSize(
648 QuicTransportVersion version,
649 const QuicWindowUpdateFrame& frame) {
650 if (version != QUIC_VERSION_99) {
651 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
652 }
653 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
654 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
655 return kQuicFrameTypeSize +
656 QuicDataWriter::GetVarInt62Len(frame.byte_offset);
657 }
658 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
659 // fields.
660 return kQuicFrameTypeSize +
661 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
662 QuicDataWriter::GetVarInt62Len(frame.stream_id);
663}
664
665// static
666size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
667 const QuicMaxStreamIdFrame& frame) {
668 if (version != QUIC_VERSION_99) {
669 QUIC_BUG << "In version " << version
670 << " - not 99 - and tried to serialize MaxStreamId Frame.";
671 }
672
673 // Convert from the stream id on which the connection is blocked to a count
674 QuicStreamId stream_count = StreamIdToCount(version, frame.max_stream_id);
675
676 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_count);
677}
678
679// static
680size_t QuicFramer::GetStreamsBlockedFrameSize(
681 QuicTransportVersion version,
682 const QuicStreamIdBlockedFrame& frame) {
683 if (version != QUIC_VERSION_99) {
684 QUIC_BUG << "In version " << version
685 << " - not 99 - and tried to serialize StreamIdBlocked Frame.";
686 }
687
688 // Convert from the stream id on which the connection is blocked to a count
689 QuicStreamId stream_count = StreamIdToCount(version, frame.stream_id);
690
691 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_count);
692}
693
694// static
695size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
696 const QuicBlockedFrame& frame) {
697 if (version != QUIC_VERSION_99) {
698 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
699 }
700 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
701 // return size of IETF QUIC Blocked frame
702 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
703 }
704 // return size of IETF QUIC Stream Blocked frame.
705 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
706 QuicDataWriter::GetVarInt62Len(frame.stream_id);
707}
708
709// static
710size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
711 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
712 sizeof(QuicApplicationErrorCode);
713}
714
715// static
716size_t QuicFramer::GetPathChallengeFrameSize(
717 const QuicPathChallengeFrame& frame) {
718 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
719}
720
721// static
722size_t QuicFramer::GetPathResponseFrameSize(
723 const QuicPathResponseFrame& frame) {
724 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
725}
726
727// static
728size_t QuicFramer::GetRetransmittableControlFrameSize(
729 QuicTransportVersion version,
730 const QuicFrame& frame) {
731 switch (frame.type) {
732 case PING_FRAME:
733 // Ping has no payload.
734 return kQuicFrameTypeSize;
735 case RST_STREAM_FRAME:
736 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
737 case CONNECTION_CLOSE_FRAME:
738 return GetMinConnectionCloseFrameSize(version,
739 *frame.connection_close_frame) +
740 TruncatedErrorStringSize(
741 frame.connection_close_frame->error_details);
742 case GOAWAY_FRAME:
743 return GetMinGoAwayFrameSize() +
744 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
745 case WINDOW_UPDATE_FRAME:
746 // For version 99, this could be either a MAX DATA or MAX STREAM DATA.
747 // GetWindowUpdateFrameSize figures this out and returns the correct
748 // length.
749 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
750 case BLOCKED_FRAME:
751 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500752 case NEW_CONNECTION_ID_FRAME:
753 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
754 case RETIRE_CONNECTION_ID_FRAME:
755 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
756 case NEW_TOKEN_FRAME:
757 return GetNewTokenFrameSize(*frame.new_token_frame);
758 case MAX_STREAM_ID_FRAME:
759 return GetMaxStreamsFrameSize(version, frame.max_stream_id_frame);
760 case STREAM_ID_BLOCKED_FRAME:
761 return GetStreamsBlockedFrameSize(version, frame.stream_id_blocked_frame);
762 case PATH_RESPONSE_FRAME:
763 return GetPathResponseFrameSize(*frame.path_response_frame);
764 case PATH_CHALLENGE_FRAME:
765 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
766 case STOP_SENDING_FRAME:
767 return GetStopSendingFrameSize(*frame.stop_sending_frame);
768
769 case STREAM_FRAME:
770 case ACK_FRAME:
771 case STOP_WAITING_FRAME:
772 case MTU_DISCOVERY_FRAME:
773 case PADDING_FRAME:
774 case MESSAGE_FRAME:
775 case CRYPTO_FRAME:
776 case NUM_FRAME_TYPES:
777 DCHECK(false);
778 return 0;
779 }
780
781 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
782 DCHECK(false);
783 return 0;
784}
785
786// static
787size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
788 // Sizes are 1 through 4 bytes.
789 for (int i = 1; i <= 4; ++i) {
790 stream_id >>= 8;
791 if (stream_id == 0) {
792 return i;
793 }
794 }
795 QUIC_BUG << "Failed to determine StreamIDSize.";
796 return 4;
797}
798
799// static
800size_t QuicFramer::GetStreamOffsetSize(QuicTransportVersion version,
801 QuicStreamOffset offset) {
802 // 0 is a special case.
803 if (offset == 0) {
804 return 0;
805 }
806 // 2 through 8 are the remaining sizes.
807 offset >>= 8;
808 for (int i = 2; i <= 8; ++i) {
809 offset >>= 8;
810 if (offset == 0) {
811 return i;
812 }
813 }
814 QUIC_BUG << "Failed to determine StreamOffsetSize.";
815 return 8;
816}
817
818// static
819size_t QuicFramer::GetNewConnectionIdFrameSize(
820 const QuicNewConnectionIdFrame& frame) {
821 return kQuicFrameTypeSize +
822 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
823 kConnectionIdLengthSize + frame.connection_id.length() +
824 sizeof(frame.stateless_reset_token);
825}
826
827// static
828size_t QuicFramer::GetRetireConnectionIdFrameSize(
829 const QuicRetireConnectionIdFrame& frame) {
830 return kQuicFrameTypeSize +
831 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
832}
833
834// static
835size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
836 return kQuicFrameTypeSize +
837 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
838 frame.token.length();
839}
840
841// TODO(nharper): Change this method to take a ParsedQuicVersion.
842bool QuicFramer::IsSupportedTransportVersion(
843 const QuicTransportVersion version) const {
844 for (ParsedQuicVersion supported_version : supported_versions_) {
845 if (version == supported_version.transport_version) {
846 return true;
847 }
848 }
849 return false;
850}
851
852bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
853 for (const ParsedQuicVersion& supported_version : supported_versions_) {
854 if (version == supported_version) {
855 return true;
856 }
857 }
858 return false;
859}
860
861size_t QuicFramer::GetSerializedFrameLength(
862 const QuicFrame& frame,
863 size_t free_bytes,
864 bool first_frame,
865 bool last_frame,
866 QuicPacketNumberLength packet_number_length) {
867 // Prevent a rare crash reported in b/19458523.
868 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
869 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
870 << free_bytes << " first_frame:" << first_frame
871 << " last_frame:" << last_frame
872 << " seq num length:" << packet_number_length;
873 set_error(QUIC_INTERNAL_ERROR);
874 visitor_->OnError(this);
875 return 0;
876 }
877 if (frame.type == PADDING_FRAME) {
878 if (frame.padding_frame.num_padding_bytes == -1) {
879 // Full padding to the end of the packet.
880 return free_bytes;
881 } else {
882 // Lite padding.
883 return free_bytes <
884 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
885 ? free_bytes
886 : frame.padding_frame.num_padding_bytes;
887 }
888 }
889
890 size_t frame_len =
891 ComputeFrameLength(frame, last_frame, packet_number_length);
892 if (frame_len <= free_bytes) {
893 // Frame fits within packet. Note that acks may be truncated.
894 return frame_len;
895 }
896 // Only truncate the first frame in a packet, so if subsequent ones go
897 // over, stop including more frames.
898 if (!first_frame) {
899 return 0;
900 }
901 bool can_truncate =
902 frame.type == ACK_FRAME &&
903 free_bytes >= GetMinAckFrameSize(version_.transport_version,
904 PACKET_6BYTE_PACKET_NUMBER);
905 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700906 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500907 // Note that we may not use every byte of the writer in this case.
908 QUIC_DLOG(INFO) << ENDPOINT
909 << "Truncating large frame, free bytes: " << free_bytes;
910 return free_bytes;
911 }
912 return 0;
913}
914
915QuicFramer::AckFrameInfo::AckFrameInfo()
916 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
917
918QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
919
920QuicFramer::AckFrameInfo::~AckFrameInfo() {}
921
922bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
923 QuicDataWriter* writer,
924 size_t length_field_offset,
925 EncryptionLevel level) {
926 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
927 !header.version_flag || length_field_offset == 0) {
928 return true;
929 }
930 if (writer->length() < length_field_offset ||
931 writer->length() - length_field_offset <
932 kQuicDefaultLongHeaderLengthLength) {
933 set_detailed_error("Invalid length_field_offset.");
934 QUIC_BUG << "Invalid length_field_offset.";
935 return false;
936 }
937 size_t length_to_write = writer->length() - length_field_offset -
938 kQuicDefaultLongHeaderLengthLength;
939 // Add length of auth tag.
940 length_to_write = GetCiphertextSize(level, length_to_write);
941
942 QuicDataWriter length_writer(writer->length() - length_field_offset,
943 writer->data() + length_field_offset);
944 if (!length_writer.WriteVarInt62(length_to_write,
945 kQuicDefaultLongHeaderLengthLength)) {
946 set_detailed_error("Failed to overwrite long header length.");
947 QUIC_BUG << "Failed to overwrite long header length.";
948 return false;
949 }
950 return true;
951}
952
953size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
954 const QuicFrames& frames,
955 char* buffer,
956 size_t packet_length,
957 EncryptionLevel level) {
958 QuicDataWriter writer(packet_length, buffer);
959 size_t length_field_offset = 0;
960 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
961 QUIC_BUG << "AppendPacketHeader failed";
962 return 0;
963 }
964
965 if (transport_version() == QUIC_VERSION_99) {
966 if (AppendIetfFrames(frames, &writer) == 0) {
967 return 0;
968 }
969 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
970 level)) {
971 return 0;
972 }
973 return writer.length();
974 }
975 // TODO(dschinazi) if we enable long header lengths before v99, we need to
976 // add support for fixing up lengths in QuicFramer::BuildDataPacket.
977 DCHECK(!QuicVersionHasLongHeaderLengths(transport_version()));
978
979 size_t i = 0;
980 for (const QuicFrame& frame : frames) {
981 // Determine if we should write stream frame length in header.
982 const bool last_frame_in_packet = i == frames.size() - 1;
983 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
984 QUIC_BUG << "AppendTypeByte failed";
985 return 0;
986 }
987
988 switch (frame.type) {
989 case PADDING_FRAME:
990 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
991 QUIC_BUG << "AppendPaddingFrame of "
992 << frame.padding_frame.num_padding_bytes << " failed";
993 return 0;
994 }
995 break;
996 case STREAM_FRAME:
997 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
998 &writer)) {
999 QUIC_BUG << "AppendStreamFrame failed";
1000 return 0;
1001 }
1002 break;
1003 case ACK_FRAME:
1004 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
1005 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
1006 return 0;
1007 }
1008 break;
1009 case STOP_WAITING_FRAME:
1010 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
1011 &writer)) {
1012 QUIC_BUG << "AppendStopWaitingFrame failed";
1013 return 0;
1014 }
1015 break;
1016 case MTU_DISCOVERY_FRAME:
1017 // MTU discovery frames are serialized as ping frames.
1018 QUIC_FALLTHROUGH_INTENDED;
1019 case PING_FRAME:
1020 // Ping has no payload.
1021 break;
1022 case RST_STREAM_FRAME:
1023 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
1024 QUIC_BUG << "AppendRstStreamFrame failed";
1025 return 0;
1026 }
1027 break;
1028 case CONNECTION_CLOSE_FRAME:
1029 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
1030 &writer)) {
1031 QUIC_BUG << "AppendConnectionCloseFrame failed";
1032 return 0;
1033 }
1034 break;
1035 case GOAWAY_FRAME:
1036 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
1037 QUIC_BUG << "AppendGoAwayFrame failed";
1038 return 0;
1039 }
1040 break;
1041 case WINDOW_UPDATE_FRAME:
1042 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
1043 QUIC_BUG << "AppendWindowUpdateFrame failed";
1044 return 0;
1045 }
1046 break;
1047 case BLOCKED_FRAME:
1048 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
1049 QUIC_BUG << "AppendBlockedFrame failed";
1050 return 0;
1051 }
1052 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001053 case NEW_CONNECTION_ID_FRAME:
1054 set_detailed_error(
1055 "Attempt to append NEW_CONNECTION_ID frame and not in version 99.");
1056 return RaiseError(QUIC_INTERNAL_ERROR);
1057 case RETIRE_CONNECTION_ID_FRAME:
1058 set_detailed_error(
1059 "Attempt to append RETIRE_CONNECTION_ID frame and not in version "
1060 "99.");
1061 return RaiseError(QUIC_INTERNAL_ERROR);
1062 case NEW_TOKEN_FRAME:
1063 set_detailed_error(
1064 "Attempt to append NEW_TOKEN_ID frame and not in version 99.");
1065 return RaiseError(QUIC_INTERNAL_ERROR);
1066 case MAX_STREAM_ID_FRAME:
1067 set_detailed_error(
1068 "Attempt to append MAX_STREAM_ID frame and not in version 99.");
1069 return RaiseError(QUIC_INTERNAL_ERROR);
1070 case STREAM_ID_BLOCKED_FRAME:
1071 set_detailed_error(
1072 "Attempt to append STREAM_ID_BLOCKED frame and not in version 99.");
1073 return RaiseError(QUIC_INTERNAL_ERROR);
1074 case PATH_RESPONSE_FRAME:
1075 set_detailed_error(
1076 "Attempt to append PATH_RESPONSE frame and not in version 99.");
1077 return RaiseError(QUIC_INTERNAL_ERROR);
1078 case PATH_CHALLENGE_FRAME:
1079 set_detailed_error(
1080 "Attempt to append PATH_CHALLENGE frame and not in version 99.");
1081 return RaiseError(QUIC_INTERNAL_ERROR);
1082 case STOP_SENDING_FRAME:
1083 set_detailed_error(
1084 "Attempt to append STOP_SENDING frame and not in version 99.");
1085 return RaiseError(QUIC_INTERNAL_ERROR);
1086 case MESSAGE_FRAME:
1087 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1088 last_frame_in_packet, &writer)) {
1089 QUIC_BUG << "AppendMessageFrame failed";
1090 return 0;
1091 }
1092 break;
1093 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -07001094 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001095 set_detailed_error(
1096 "Attempt to append CRYPTO frame in version prior to 47.");
1097 return RaiseError(QUIC_INTERNAL_ERROR);
1098 }
1099 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1100 QUIC_BUG << "AppendCryptoFrame failed";
1101 return 0;
1102 }
1103 break;
1104 default:
1105 RaiseError(QUIC_INVALID_FRAME_DATA);
1106 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1107 return 0;
1108 }
1109 ++i;
1110 }
1111
1112 return writer.length();
1113}
1114
1115size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1116 QuicDataWriter* writer) {
1117 size_t i = 0;
1118 for (const QuicFrame& frame : frames) {
1119 // Determine if we should write stream frame length in header.
1120 const bool last_frame_in_packet = i == frames.size() - 1;
1121 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1122 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1123 return 0;
1124 }
1125
1126 switch (frame.type) {
1127 case PADDING_FRAME:
1128 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1129 QUIC_BUG << "AppendPaddingFrame of "
1130 << frame.padding_frame.num_padding_bytes
1131 << " failed: " << detailed_error();
1132 return 0;
1133 }
1134 break;
1135 case STREAM_FRAME:
1136 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1137 writer)) {
1138 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1139 return 0;
1140 }
1141 break;
1142 case ACK_FRAME:
1143 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001144 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1145 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001146 return 0;
1147 }
1148 break;
1149 case STOP_WAITING_FRAME:
1150 set_detailed_error(
1151 "Attempt to append STOP WAITING frame in version 99.");
1152 return RaiseError(QUIC_INTERNAL_ERROR);
1153 case MTU_DISCOVERY_FRAME:
1154 // MTU discovery frames are serialized as ping frames.
1155 QUIC_FALLTHROUGH_INTENDED;
1156 case PING_FRAME:
1157 // Ping has no payload.
1158 break;
1159 case RST_STREAM_FRAME:
1160 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1161 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1162 return 0;
1163 }
1164 break;
1165 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001166 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1167 writer)) {
1168 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1169 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001170 return 0;
1171 }
1172 break;
1173 case GOAWAY_FRAME:
1174 set_detailed_error("Attempt to append GOAWAY frame in version 99.");
1175 return RaiseError(QUIC_INTERNAL_ERROR);
1176 case WINDOW_UPDATE_FRAME:
1177 // Depending on whether there is a stream ID or not, will be either a
1178 // MAX STREAM DATA frame or a MAX DATA frame.
1179 if (frame.window_update_frame->stream_id ==
1180 QuicUtils::GetInvalidStreamId(transport_version())) {
1181 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1182 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1183 return 0;
1184 }
1185 } else {
1186 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1187 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1188 return 0;
1189 }
1190 }
1191 break;
1192 case BLOCKED_FRAME:
1193 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1194 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1195 return 0;
1196 }
1197 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001198 case MAX_STREAM_ID_FRAME:
1199 if (!AppendMaxStreamsFrame(frame.max_stream_id_frame, writer)) {
1200 QUIC_BUG << "AppendMaxStreamsFrame failed" << detailed_error();
1201 return 0;
1202 }
1203 break;
1204 case STREAM_ID_BLOCKED_FRAME:
1205 if (!AppendStreamsBlockedFrame(frame.stream_id_blocked_frame, writer)) {
1206 QUIC_BUG << "AppendStreamsBlockedFrame failed" << detailed_error();
1207 return 0;
1208 }
1209 break;
1210 case NEW_CONNECTION_ID_FRAME:
1211 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1212 writer)) {
1213 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1214 return 0;
1215 }
1216 break;
1217 case RETIRE_CONNECTION_ID_FRAME:
1218 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1219 writer)) {
1220 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1221 << detailed_error();
1222 return 0;
1223 }
1224 break;
1225 case NEW_TOKEN_FRAME:
1226 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1227 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1228 return 0;
1229 }
1230 break;
1231 case STOP_SENDING_FRAME:
1232 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1233 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1234 return 0;
1235 }
1236 break;
1237 case PATH_CHALLENGE_FRAME:
1238 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1239 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1240 return 0;
1241 }
1242 break;
1243 case PATH_RESPONSE_FRAME:
1244 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1245 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1246 return 0;
1247 }
1248 break;
1249 case MESSAGE_FRAME:
1250 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1251 last_frame_in_packet, writer)) {
1252 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1253 return 0;
1254 }
1255 break;
1256 case CRYPTO_FRAME:
1257 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1258 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1259 return 0;
1260 }
1261 break;
1262 default:
1263 RaiseError(QUIC_INVALID_FRAME_DATA);
1264 set_detailed_error("Tried to append unknown frame type.");
1265 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1266 return 0;
1267 }
1268 ++i;
1269 }
1270
1271 return writer->length();
1272}
1273
rch67cb9df2019-03-26 16:52:07 -07001274size_t QuicFramer::BuildConnectivityProbingPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001275 const QuicPacketHeader& header,
1276 char* buffer,
1277 size_t packet_length,
1278 EncryptionLevel level) {
1279 QuicFrames frames;
1280
1281 // Write a PING frame, which has no data payload.
1282 QuicPingFrame ping_frame;
1283 frames.push_back(QuicFrame(ping_frame));
1284
1285 // Add padding to the rest of the packet.
1286 QuicPaddingFrame padding_frame;
1287 frames.push_back(QuicFrame(padding_frame));
1288
1289 return BuildDataPacket(header, frames, buffer, packet_length, level);
1290}
1291
QUICHE teama6ef0a62019-03-07 20:34:33 -05001292size_t QuicFramer::BuildPaddedPathChallengePacket(
1293 const QuicPacketHeader& header,
1294 char* buffer,
1295 size_t packet_length,
1296 QuicPathFrameBuffer* payload,
1297 QuicRandom* randomizer,
1298 EncryptionLevel level) {
1299 if (version_.transport_version != QUIC_VERSION_99) {
1300 QUIC_BUG << "Attempt to build a PATH_CHALLENGE Connectivity Probing "
1301 "packet and not doing IETF QUIC";
1302 return 0;
1303 }
1304 QuicFrames frames;
1305
1306 // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1307 randomizer->RandBytes(payload->data(), payload->size());
1308
1309 QuicPathChallengeFrame path_challenge_frame(0, *payload);
1310 frames.push_back(QuicFrame(&path_challenge_frame));
1311
1312 // Add padding to the rest of the packet in order to assess Path MTU
1313 // characteristics.
1314 QuicPaddingFrame padding_frame;
1315 frames.push_back(QuicFrame(padding_frame));
1316
1317 return BuildDataPacket(header, frames, buffer, packet_length, level);
1318}
1319
1320size_t QuicFramer::BuildPathResponsePacket(
1321 const QuicPacketHeader& header,
1322 char* buffer,
1323 size_t packet_length,
1324 const QuicDeque<QuicPathFrameBuffer>& payloads,
1325 const bool is_padded,
1326 EncryptionLevel level) {
1327 if (payloads.empty()) {
1328 QUIC_BUG
1329 << "Attempt to generate connectivity response with no request payloads";
1330 return 0;
1331 }
1332 if (version_.transport_version != QUIC_VERSION_99) {
1333 QUIC_BUG << "Attempt to build a PATH_RESPONSE Connectivity Probing "
1334 "packet and not doing IETF QUIC";
1335 return 0;
1336 }
1337
1338 std::vector<std::unique_ptr<QuicPathResponseFrame>> path_response_frames;
1339 for (const QuicPathFrameBuffer& payload : payloads) {
1340 // Note that the control frame ID can be 0 since this is not retransmitted.
1341 path_response_frames.push_back(
1342 QuicMakeUnique<QuicPathResponseFrame>(0, payload));
1343 }
1344
1345 QuicFrames frames;
1346 for (const std::unique_ptr<QuicPathResponseFrame>& path_response_frame :
1347 path_response_frames) {
1348 frames.push_back(QuicFrame(path_response_frame.get()));
1349 }
1350
1351 if (is_padded) {
1352 // Add padding to the rest of the packet in order to assess Path MTU
1353 // characteristics.
1354 QuicPaddingFrame padding_frame;
1355 frames.push_back(QuicFrame(padding_frame));
1356 }
1357
1358 return BuildDataPacket(header, frames, buffer, packet_length, level);
1359}
1360
1361// static
1362std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1363 const QuicPublicResetPacket& packet) {
1364 CryptoHandshakeMessage reset;
1365 reset.set_tag(kPRST);
1366 reset.SetValue(kRNON, packet.nonce_proof);
1367 if (packet.client_address.host().address_family() !=
1368 IpAddressFamily::IP_UNSPEC) {
1369 // packet.client_address is non-empty.
1370 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001371 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001372 if (serialized_address.empty()) {
1373 return nullptr;
1374 }
1375 reset.SetStringPiece(kCADR, serialized_address);
1376 }
1377 if (!packet.endpoint_id.empty()) {
1378 reset.SetStringPiece(kEPID, packet.endpoint_id);
1379 }
1380 const QuicData& reset_serialized = reset.GetSerialized();
1381
1382 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1383 reset_serialized.length();
1384 std::unique_ptr<char[]> buffer(new char[len]);
1385 // Endianness is not a concern here, as writer is not going to write integers
1386 // or floating numbers.
1387 QuicDataWriter writer(len, buffer.get());
1388
1389 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1390 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1391 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1392 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1393 if (!writer.WriteUInt8(flags)) {
1394 return nullptr;
1395 }
1396
1397 if (!writer.WriteConnectionId(packet.connection_id)) {
1398 return nullptr;
1399 }
1400
1401 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1402 return nullptr;
1403 }
1404
1405 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1406}
1407
1408// static
1409std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
1410 QuicConnectionId connection_id,
1411 QuicUint128 stateless_reset_token) {
1412 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1413 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1414 sizeof(stateless_reset_token);
1415 std::unique_ptr<char[]> buffer(new char[len]);
1416 QuicDataWriter writer(len, buffer.get());
1417
1418 uint8_t type = 0;
1419 type |= FLAGS_FIXED_BIT;
1420 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1421 type |= FLAGS_SHORT_HEADER_RESERVED_2;
1422 type |= PacketNumberLengthToOnWireValue(QUIC_VERSION_UNSUPPORTED,
1423 PACKET_1BYTE_PACKET_NUMBER);
1424
1425 // Append type byte.
1426 if (!writer.WriteUInt8(type)) {
1427 return nullptr;
1428 }
1429 // Append random bytes.
1430 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1431 kMinRandomBytesLengthInStatelessReset)) {
1432 return nullptr;
1433 }
1434
1435 // Append stateless reset token.
1436 if (!writer.WriteBytes(&stateless_reset_token,
1437 sizeof(stateless_reset_token))) {
1438 return nullptr;
1439 }
1440 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1441}
1442
1443// static
1444std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
1445 QuicConnectionId connection_id,
1446 bool ietf_quic,
1447 const ParsedQuicVersionVector& versions) {
1448 if (ietf_quic) {
1449 return BuildIetfVersionNegotiationPacket(connection_id, versions);
1450 }
1451 DCHECK(!versions.empty());
1452 size_t len = kPublicFlagsSize + connection_id.length() +
1453 versions.size() * kQuicVersionSize;
1454 std::unique_ptr<char[]> buffer(new char[len]);
1455 // Endianness is not a concern here, version negotiation packet does not have
1456 // integers or floating numbers.
1457 QuicDataWriter writer(len, buffer.get());
1458
1459 uint8_t flags = static_cast<uint8_t>(
1460 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1461 // TODO(rch): Remove this QUIC_VERSION_32 is retired.
1462 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1463 if (!writer.WriteUInt8(flags)) {
1464 return nullptr;
1465 }
1466
1467 if (!writer.WriteConnectionId(connection_id)) {
1468 return nullptr;
1469 }
1470
1471 for (const ParsedQuicVersion& version : versions) {
1472 // TODO(rch): Use WriteUInt32() once QUIC_VERSION_35 is removed.
1473 if (!writer.WriteTag(
1474 QuicEndian::HostToNet32(CreateQuicVersionLabel(version)))) {
1475 return nullptr;
1476 }
1477 }
1478
1479 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1480}
1481
1482// static
1483std::unique_ptr<QuicEncryptedPacket>
1484QuicFramer::BuildIetfVersionNegotiationPacket(
1485 QuicConnectionId connection_id,
1486 const ParsedQuicVersionVector& versions) {
1487 QUIC_DVLOG(1) << "Building IETF version negotiation packet.";
1488 DCHECK(!versions.empty());
1489 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
1490 connection_id.length() +
1491 (versions.size() + 1) * kQuicVersionSize;
1492 std::unique_ptr<char[]> buffer(new char[len]);
1493 QuicDataWriter writer(len, buffer.get());
1494
1495 // TODO(fayang): Randomly select a value for the type.
1496 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | VERSION_NEGOTIATION);
1497 if (!writer.WriteUInt8(type)) {
1498 return nullptr;
1499 }
1500
1501 if (!writer.WriteUInt32(0)) {
1502 return nullptr;
1503 }
1504
1505 if (!GetQuicReloadableFlag(quic_use_new_append_connection_id)) {
1506 if (!AppendIetfConnectionId(true, EmptyQuicConnectionId(),
1507 PACKET_0BYTE_CONNECTION_ID, connection_id,
1508 PACKET_8BYTE_CONNECTION_ID, &writer)) {
1509 return nullptr;
1510 }
1511 } else {
1512 QUIC_RELOADABLE_FLAG_COUNT_N(quic_use_new_append_connection_id, 1, 2);
1513 if (!AppendIetfConnectionIdsNew(true, EmptyQuicConnectionId(),
1514 connection_id, &writer)) {
1515 return nullptr;
1516 }
1517 }
1518
1519 for (const ParsedQuicVersion& version : versions) {
1520 // TODO(rch): Use WriteUInt32() once QUIC_VERSION_35 is removed.
1521 if (!writer.WriteTag(
1522 QuicEndian::HostToNet32(CreateQuicVersionLabel(version)))) {
1523 return nullptr;
1524 }
1525 }
1526
1527 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1528}
1529
1530bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1531 QuicDataReader reader(packet.data(), packet.length());
1532
1533 bool packet_has_ietf_packet_header = false;
1534 if (infer_packet_header_type_from_version_) {
1535 packet_has_ietf_packet_header =
1536 version_.transport_version > QUIC_VERSION_43;
1537 } else if (!reader.IsDoneReading()) {
1538 uint8_t type = reader.PeekByte();
1539 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1540 }
1541 if (packet_has_ietf_packet_header) {
1542 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1543 }
1544
1545 visitor_->OnPacket();
1546
1547 QuicPacketHeader header;
1548 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1549 DCHECK_NE("", detailed_error_);
1550 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1551 << detailed_error_;
1552 DCHECK_NE("", detailed_error_);
1553 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1554 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1555 }
1556
1557 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1558 // The visitor suppresses further processing of the packet.
1559 return true;
1560 }
1561
1562 if (perspective_ == Perspective::IS_SERVER && header.version_flag &&
1563 header.version != version_) {
1564 if (!visitor_->OnProtocolVersionMismatch(header.version, header.form)) {
1565 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1566 return true;
1567 }
1568 }
1569
1570 bool rv;
1571 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
1572 QUIC_DVLOG(1) << ENDPOINT << "Received version negotiation packet";
1573 rv = ProcessVersionNegotiationPacket(&reader, header);
1574 } else if (header.reset_flag) {
1575 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001576 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001577 // The optimized decryption algorithm implementations run faster when
1578 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001579 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001580 if (packet_has_ietf_packet_header) {
1581 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
dschinazie8d7fa72019-04-05 14:44:40 -07001582 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001583 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001584 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1585 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001586 }
1587 } else {
1588 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1589 if (packet_has_ietf_packet_header) {
1590 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1591 packet.length());
1592 } else {
1593 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1594 packet.length());
1595 }
1596 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001597 << "than kMaxIncomingPacketSize. packet size:"
1598 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001599 }
1600 return rv;
1601}
1602
1603bool QuicFramer::ProcessVersionNegotiationPacket(
1604 QuicDataReader* reader,
1605 const QuicPacketHeader& header) {
1606 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1607
1608 QuicVersionNegotiationPacket packet(header.destination_connection_id);
1609 // Try reading at least once to raise error if the packet is invalid.
1610 do {
1611 QuicVersionLabel version_label;
1612 if (!reader->ReadTag(&version_label)) {
1613 set_detailed_error("Unable to read supported version in negotiation.");
1614 RecordDroppedPacketReason(
1615 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1616 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1617 }
1618 // TODO(rch): Use ReadUInt32() once QUIC_VERSION_35 is removed.
1619 version_label = QuicEndian::NetToHost32(version_label);
1620 packet.versions.push_back(ParseQuicVersionLabel(version_label));
1621 } while (!reader->IsDoneReading());
1622
1623 visitor_->OnVersionNegotiationPacket(packet);
1624 return true;
1625}
1626
1627bool QuicFramer::MaybeProcessIetfInitialRetryToken(
1628 QuicDataReader* encrypted_reader,
1629 QuicPacketHeader* header) {
1630 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1631 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1632 header->long_packet_type != INITIAL) {
1633 return true;
1634 }
1635 uint64_t retry_token_length = 0;
1636 header->retry_token_length_length = encrypted_reader->PeekVarInt62Length();
1637 if (!encrypted_reader->ReadVarInt62(&retry_token_length)) {
1638 set_detailed_error("Unable to read INITIAL retry token length.");
1639 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1640 }
1641 header->retry_token = encrypted_reader->PeekRemainingPayload();
1642 // Safety check to avoid spending ressources if malformed.
1643 // At this point header->retry_token contains the rest of the packet
1644 // so its length() is the amount of data remaining in the packet.
1645 if (retry_token_length > header->retry_token.length()) {
1646 set_detailed_error("INITIAL token length longer than packet.");
1647 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1648 }
1649 // Resize retry_token to make it only contain the retry token.
1650 header->retry_token.remove_suffix(header->retry_token.length() -
1651 retry_token_length);
1652 // Advance encrypted_reader by retry_token_length.
1653 uint8_t wasted_byte;
1654 for (uint64_t i = 0; i < retry_token_length; ++i) {
1655 if (!encrypted_reader->ReadUInt8(&wasted_byte)) {
1656 set_detailed_error("Unable to read INITIAL retry token.");
1657 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1658 }
1659 }
1660 return true;
1661}
1662
1663// Seeks the current packet to check for a coalesced packet at the end.
1664// If the IETF length field only spans part of the outer packet,
1665// then there is a coalesced packet after this one.
1666void QuicFramer::MaybeProcessCoalescedPacket(
1667 const QuicDataReader& encrypted_reader,
1668 uint64_t remaining_bytes_length,
1669 const QuicPacketHeader& header) {
1670 if (header.remaining_packet_length >= remaining_bytes_length) {
1671 // There is no coalesced packet.
1672 return;
1673 }
1674
1675 QuicStringPiece remaining_data = encrypted_reader.PeekRemainingPayload();
1676 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1677
1678 const char* coalesced_data =
1679 remaining_data.data() + header.remaining_packet_length;
1680 uint64_t coalesced_data_length =
1681 remaining_bytes_length - header.remaining_packet_length;
1682 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1683
1684 QuicPacketHeader coalesced_header;
1685 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1686 QUIC_PEER_BUG << ENDPOINT
1687 << "Failed to parse received coalesced header of length "
1688 << coalesced_data_length << ": "
1689 << QuicTextUtils::HexEncode(coalesced_data,
1690 coalesced_data_length)
1691 << " previous header was " << header;
1692 return;
1693 }
1694
1695 if (coalesced_header.destination_connection_id !=
1696 header.destination_connection_id ||
1697 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1698 coalesced_header.version != header.version)) {
1699 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1700 << coalesced_header << " previous header was " << header;
1701 return;
1702 }
1703
1704 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1705 /*owns_buffer=*/false);
1706 visitor_->OnCoalescedPacket(coalesced_packet);
1707}
1708
1709bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1710 QuicPacketHeader* header) {
1711 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1712 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1713 (header->long_packet_type != INITIAL &&
1714 header->long_packet_type != HANDSHAKE &&
1715 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1716 return true;
1717 }
1718 header->length_length = encrypted_reader->PeekVarInt62Length();
1719 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1720 set_detailed_error("Unable to read long header payload length.");
1721 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1722 }
1723 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1724 if (header->remaining_packet_length > remaining_bytes_length) {
1725 set_detailed_error("Long header payload length longer than packet.");
1726 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1727 }
1728
1729 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1730 *header);
1731
1732 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1733 set_detailed_error("Length TruncateRemaining failed.");
1734 QUIC_BUG << "Length TruncateRemaining failed.";
1735 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1736 }
1737 return true;
1738}
1739
1740bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1741 QuicPacketHeader* header,
1742 const QuicEncryptedPacket& packet,
1743 char* decrypted_buffer,
1744 size_t buffer_length) {
1745 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1746 DCHECK(!header->has_possible_stateless_reset_token);
1747 header->retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1748 header->retry_token = QuicStringPiece();
1749 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1750 header->remaining_packet_length = 0;
1751 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1752 perspective_ == Perspective::IS_CLIENT) {
1753 // Peek possible stateless reset token. Will only be used on decryption
1754 // failure.
1755 QuicStringPiece remaining = encrypted_reader->PeekRemainingPayload();
1756 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1757 header->has_possible_stateless_reset_token = true;
1758 memcpy(&header->possible_stateless_reset_token,
1759 &remaining.data()[remaining.length() -
1760 sizeof(header->possible_stateless_reset_token)],
1761 sizeof(header->possible_stateless_reset_token));
1762 }
1763 }
1764
1765 if (!MaybeProcessIetfInitialRetryToken(encrypted_reader, header)) {
1766 return false;
1767 }
1768
1769 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1770 return false;
1771 }
1772
1773 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1774 header->long_packet_type != VERSION_NEGOTIATION) {
1775 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001776 QuicPacketNumber base_packet_number;
1777 if (supports_multiple_packet_number_spaces_) {
1778 base_packet_number =
1779 largest_decrypted_packet_numbers_[GetPacketNumberSpace(*header)];
1780 } else {
1781 base_packet_number = largest_packet_number_;
1782 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001783 uint64_t full_packet_number;
1784 if (!ProcessAndCalculatePacketNumber(
1785 encrypted_reader, header->packet_number_length, base_packet_number,
1786 &full_packet_number)) {
1787 set_detailed_error("Unable to read packet number.");
1788 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1789 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1790 }
1791
1792 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
1793 if (IsIetfStatelessResetPacket(*header)) {
1794 // This is a stateless reset packet.
1795 QuicIetfStatelessResetPacket packet(
1796 *header, header->possible_stateless_reset_token);
1797 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1798 return true;
1799 }
1800 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1801 set_detailed_error("packet numbers cannot be 0.");
1802 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1803 }
1804 header->packet_number = QuicPacketNumber(full_packet_number);
1805 }
1806
1807 // A nonce should only present in SHLO from the server to the client when
1808 // using QUIC crypto.
1809 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1810 header->long_packet_type == ZERO_RTT_PROTECTED &&
1811 perspective_ == Perspective::IS_CLIENT &&
1812 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1813 if (!encrypted_reader->ReadBytes(
1814 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1815 last_nonce_.size())) {
1816 set_detailed_error("Unable to read nonce.");
1817 RecordDroppedPacketReason(
1818 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1819 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1820 }
1821
1822 header->nonce = &last_nonce_;
1823 } else {
1824 header->nonce = nullptr;
1825 }
1826
1827 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1828 set_detailed_error(
1829 "Visitor asked to stop processing of unauthenticated header.");
1830 return false;
1831 }
1832
1833 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1834 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1835 version_.transport_version, packet,
1836 GetIncludedDestinationConnectionIdLength(*header),
1837 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1838 header->nonce != nullptr, header->packet_number_length,
1839 header->retry_token_length_length, header->retry_token.length(),
1840 header->length_length);
1841
1842 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001843 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001844 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001845 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001846 if (IsIetfStatelessResetPacket(*header)) {
1847 // This is a stateless reset packet.
1848 QuicIetfStatelessResetPacket packet(
1849 *header, header->possible_stateless_reset_token);
1850 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1851 return true;
1852 }
1853 set_detailed_error("Unable to decrypt payload.");
1854 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1855 return RaiseError(QUIC_DECRYPTION_FAILURE);
1856 }
1857 QuicDataReader reader(decrypted_buffer, decrypted_length);
1858
1859 // Update the largest packet number after we have decrypted the packet
1860 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001861 if (supports_multiple_packet_number_spaces_) {
1862 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1863 decrypted_level)]
1864 .UpdateMax(header->packet_number);
1865 } else {
1866 largest_packet_number_.UpdateMax(header->packet_number);
1867 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001868
1869 if (!visitor_->OnPacketHeader(*header)) {
1870 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1871 // The visitor suppresses further processing of the packet.
1872 return true;
1873 }
1874
dschinazie8d7fa72019-04-05 14:44:40 -07001875 if (packet.length() > kMaxIncomingPacketSize) {
1876 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001877 return RaiseError(QUIC_PACKET_TOO_LARGE);
1878 }
1879
1880 // Handle the payload.
1881 if (version_.transport_version == QUIC_VERSION_99) {
1882 if (!ProcessIetfFrameData(&reader, *header)) {
1883 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1884 DCHECK_NE("", detailed_error_);
1885 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1886 << detailed_error_;
1887 return false;
1888 }
1889 } else {
1890 if (!ProcessFrameData(&reader, *header)) {
1891 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1892 DCHECK_NE("", detailed_error_);
1893 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1894 << detailed_error_;
1895 return false;
1896 }
1897 }
1898
1899 visitor_->OnPacketComplete();
1900 return true;
1901}
1902
1903bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1904 QuicPacketHeader* header,
1905 const QuicEncryptedPacket& packet,
1906 char* decrypted_buffer,
1907 size_t buffer_length) {
1908 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1909 DCHECK_NE("", detailed_error_);
1910 QUIC_DVLOG(1)
1911 << ENDPOINT
1912 << "Unable to process packet header. Stopping parsing. Error: "
1913 << detailed_error_;
1914 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1915 return false;
1916 }
1917
1918 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1919 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1920 version_.transport_version, packet,
1921 GetIncludedDestinationConnectionIdLength(*header),
1922 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1923 header->nonce != nullptr, header->packet_number_length,
1924 header->retry_token_length_length, header->retry_token.length(),
1925 header->length_length);
1926
1927 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001928 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001929 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001930 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001931 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1932 set_detailed_error("Unable to decrypt payload.");
1933 return RaiseError(QUIC_DECRYPTION_FAILURE);
1934 }
1935
1936 QuicDataReader reader(decrypted_buffer, decrypted_length);
1937
1938 // Update the largest packet number after we have decrypted the packet
1939 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001940 if (supports_multiple_packet_number_spaces_) {
1941 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1942 decrypted_level)]
1943 .UpdateMax(header->packet_number);
1944 } else {
1945 largest_packet_number_.UpdateMax(header->packet_number);
1946 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001947
1948 if (!visitor_->OnPacketHeader(*header)) {
1949 // The visitor suppresses further processing of the packet.
1950 return true;
1951 }
1952
dschinazie8d7fa72019-04-05 14:44:40 -07001953 if (packet.length() > kMaxIncomingPacketSize) {
1954 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001955 return RaiseError(QUIC_PACKET_TOO_LARGE);
1956 }
1957
1958 // Handle the payload.
1959 if (!ProcessFrameData(&reader, *header)) {
1960 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1961 DCHECK_NE("", detailed_error_);
1962 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1963 << detailed_error_;
1964 return false;
1965 }
1966
1967 visitor_->OnPacketComplete();
1968 return true;
1969}
1970
1971bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1972 const QuicPacketHeader& header) {
1973 QuicPublicResetPacket packet(header.destination_connection_id);
1974
1975 std::unique_ptr<CryptoHandshakeMessage> reset(
1976 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
1977 if (!reset.get()) {
1978 set_detailed_error("Unable to read reset message.");
1979 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1980 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1981 }
1982 if (reset->tag() != kPRST) {
1983 set_detailed_error("Incorrect message tag.");
1984 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1985 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1986 }
1987
1988 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
1989 set_detailed_error("Unable to read nonce proof.");
1990 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1991 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1992 }
1993 // TODO(satyamshekhar): validate nonce to protect against DoS.
1994
1995 QuicStringPiece address;
1996 if (reset->GetStringPiece(kCADR, &address)) {
1997 QuicSocketAddressCoder address_coder;
1998 if (address_coder.Decode(address.data(), address.length())) {
1999 packet.client_address =
2000 QuicSocketAddress(address_coder.ip(), address_coder.port());
2001 }
2002 }
2003
2004 QuicStringPiece endpoint_id;
2005 if (perspective_ == Perspective::IS_CLIENT &&
2006 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002007 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002008 packet.endpoint_id += '\0';
2009 }
2010
2011 visitor_->OnPublicResetPacket(packet);
2012 return true;
2013}
2014
2015bool QuicFramer::IsIetfStatelessResetPacket(
2016 const QuicPacketHeader& header) const {
2017 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2018 perspective_ != Perspective::IS_CLIENT)
2019 << "has_possible_stateless_reset_token can only be true at client side.";
2020 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2021 header.has_possible_stateless_reset_token &&
2022 visitor_->IsValidStatelessResetToken(
2023 header.possible_stateless_reset_token);
2024}
2025
2026bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2027 return encrypter_[level] != nullptr;
2028}
2029
2030bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2031 QuicDataWriter* writer,
2032 size_t* length_field_offset) {
2033 if (transport_version() > QUIC_VERSION_43) {
2034 return AppendIetfPacketHeader(header, writer, length_field_offset);
2035 }
2036 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2037 uint8_t public_flags = 0;
2038 if (header.reset_flag) {
2039 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2040 }
2041 if (header.version_flag) {
2042 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2043 }
2044
2045 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2046 << kPublicHeaderSequenceNumberShift;
2047
2048 if (header.nonce != nullptr) {
2049 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2050 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2051 }
2052 DCHECK_EQ(CONNECTION_ID_ABSENT, header.source_connection_id_included);
2053 switch (header.destination_connection_id_included) {
2054 case CONNECTION_ID_ABSENT:
2055 if (!writer->WriteUInt8(public_flags |
2056 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2057 return false;
2058 }
2059 break;
2060 case CONNECTION_ID_PRESENT:
2061 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
2062 header.destination_connection_id, transport_version()))
2063 << "AppendPacketHeader: attempted to use connection ID "
2064 << header.destination_connection_id
2065 << " which is invalid with version "
2066 << QuicVersionToString(transport_version());
2067
2068 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2069 if (perspective_ == Perspective::IS_CLIENT) {
2070 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2071 }
2072 if (!writer->WriteUInt8(public_flags) ||
2073 !writer->WriteConnectionId(header.destination_connection_id)) {
2074 return false;
2075 }
2076 break;
2077 }
2078 last_serialized_connection_id_ = header.destination_connection_id;
2079
2080 if (header.version_flag) {
2081 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2082 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
2083 // TODO(rch): Use WriteUInt32() once QUIC_VERSION_35 is removed.
2084 if (!writer->WriteTag(QuicEndian::NetToHost32(version_label))) {
2085 return false;
2086 }
2087
2088 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2089 << QuicVersionLabelToString(version_label) << "'";
2090 }
2091
2092 if (header.nonce != nullptr &&
2093 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2094 return false;
2095 }
2096
2097 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2098 writer)) {
2099 return false;
2100 }
2101
2102 return true;
2103}
2104
2105bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2106 QuicDataWriter* writer) {
2107 uint8_t type = 0;
2108 if (transport_version() > QUIC_VERSION_44) {
2109 if (header.version_flag) {
2110 type = static_cast<uint8_t>(
2111 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2112 LongHeaderTypeToOnWireValue(transport_version(),
2113 header.long_packet_type) |
2114 PacketNumberLengthToOnWireValue(transport_version(),
2115 header.packet_number_length));
2116 } else {
2117 type = static_cast<uint8_t>(
2118 FLAGS_FIXED_BIT |
2119 PacketNumberLengthToOnWireValue(transport_version(),
2120 header.packet_number_length));
2121 }
2122 return writer->WriteUInt8(type);
2123 }
2124
2125 if (header.version_flag) {
2126 type = static_cast<uint8_t>(
2127 FLAGS_LONG_HEADER | LongHeaderTypeToOnWireValue(
2128 transport_version(), header.long_packet_type));
2129 DCHECK_EQ(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
2130 } else {
2131 type |= FLAGS_SHORT_HEADER_RESERVED_1;
2132 type |= FLAGS_SHORT_HEADER_RESERVED_2;
2133 DCHECK_GE(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
2134 type |= PacketNumberLengthToOnWireValue(transport_version(),
2135 header.packet_number_length);
2136 }
2137 return writer->WriteUInt8(type);
2138}
2139
2140bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2141 QuicDataWriter* writer,
2142 size_t* length_field_offset) {
2143 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
2144 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
2145 header.destination_connection_id, transport_version()))
2146 << "AppendIetfPacketHeader: attempted to use connection ID "
2147 << header.destination_connection_id << " which is invalid with version "
2148 << QuicVersionToString(transport_version());
2149 if (!AppendIetfHeaderTypeByte(header, writer)) {
2150 return false;
2151 }
2152
2153 if (header.version_flag) {
2154 // Append version for long header.
2155 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
2156 // TODO(rch): Use WriteUInt32() once QUIC_VERSION_35 is removed.
2157 if (!writer->WriteTag(QuicEndian::NetToHost32(version_label))) {
2158 return false;
2159 }
2160 }
2161
2162 // Append connection ID.
2163 if (!QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2164 transport_version()) &&
2165 !GetQuicReloadableFlag(quic_use_new_append_connection_id)) {
2166 if (!AppendIetfConnectionId(
2167 header.version_flag, header.destination_connection_id,
2168 GetIncludedDestinationConnectionIdLength(header),
2169 header.source_connection_id,
2170 GetIncludedSourceConnectionIdLength(header), writer)) {
2171 return false;
2172 }
2173 } else {
2174 QUIC_RELOADABLE_FLAG_COUNT_N(quic_use_new_append_connection_id, 2, 2);
2175 if (!AppendIetfConnectionIdsNew(
2176 header.version_flag,
2177 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2178 ? header.destination_connection_id
2179 : EmptyQuicConnectionId(),
2180 header.source_connection_id_included != CONNECTION_ID_ABSENT
2181 ? header.source_connection_id
2182 : EmptyQuicConnectionId(),
2183 writer)) {
2184 return false;
2185 }
2186 }
2187 last_serialized_connection_id_ = header.destination_connection_id;
2188
2189 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2190 header.version_flag) {
2191 if (header.long_packet_type == INITIAL) {
2192 // Write retry token length.
2193 if (!writer->WriteVarInt62(header.retry_token.length(),
2194 header.retry_token_length_length)) {
2195 return false;
2196 }
2197 // Write retry token.
2198 if (!header.retry_token.empty() &&
2199 !writer->WriteStringPiece(header.retry_token)) {
2200 return false;
2201 }
2202 }
2203 if (length_field_offset != nullptr) {
2204 *length_field_offset = writer->length();
2205 }
2206 // Add fake length to reserve two bytes to add length in later.
2207 writer->WriteVarInt62(256);
2208 } else if (length_field_offset != nullptr) {
2209 *length_field_offset = 0;
2210 }
2211
2212 // Append packet number.
2213 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2214 writer)) {
2215 return false;
2216 }
2217
2218 if (!header.version_flag) {
2219 return true;
2220 }
2221
2222 if (header.nonce != nullptr) {
2223 DCHECK(header.version_flag);
2224 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2225 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2226 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2227 return false;
2228 }
2229 }
2230
2231 return true;
2232}
2233
2234const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2235 uint32_t time_delta_us) {
2236 // The new time_delta might have wrapped to the next epoch, or it
2237 // might have reverse wrapped to the previous epoch, or it might
2238 // remain in the same epoch. Select the time closest to the previous
2239 // time.
2240 //
2241 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2242 // microseconds.
2243 const uint64_t epoch_delta = UINT64_C(1) << 32;
2244 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2245 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2246 uint64_t prev_epoch = epoch - epoch_delta;
2247 uint64_t next_epoch = epoch + epoch_delta;
2248
2249 uint64_t time = ClosestTo(
2250 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2251 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2252 next_epoch + time_delta_us));
2253
2254 return QuicTime::Delta::FromMicroseconds(time);
2255}
2256
2257uint64_t QuicFramer::CalculatePacketNumberFromWire(
2258 QuicPacketNumberLength packet_number_length,
2259 QuicPacketNumber base_packet_number,
2260 uint64_t packet_number) const {
2261 // The new packet number might have wrapped to the next epoch, or
2262 // it might have reverse wrapped to the previous epoch, or it might
2263 // remain in the same epoch. Select the packet number closest to the
2264 // next expected packet number, the previous packet number plus 1.
2265
2266 // epoch_delta is the delta between epochs the packet number was serialized
2267 // with, so the correct value is likely the same epoch as the last sequence
2268 // number or an adjacent epoch.
2269 if (!base_packet_number.IsInitialized()) {
2270 return packet_number;
2271 }
2272 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2273 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2274 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2275 uint64_t prev_epoch = epoch - epoch_delta;
2276 uint64_t next_epoch = epoch + epoch_delta;
2277
2278 return ClosestTo(next_packet_number, epoch + packet_number,
2279 ClosestTo(next_packet_number, prev_epoch + packet_number,
2280 next_epoch + packet_number));
2281}
2282
2283bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2284 bool packet_has_ietf_packet_header,
2285 QuicPacketHeader* header) {
2286 if (packet_has_ietf_packet_header) {
2287 return ProcessIetfPacketHeader(reader, header);
2288 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002289 uint8_t public_flags;
2290 if (!reader->ReadBytes(&public_flags, 1)) {
2291 set_detailed_error("Unable to read public flags.");
2292 return false;
2293 }
2294
2295 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2296 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2297
2298 if (validate_flags_ && !header->version_flag &&
2299 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2300 set_detailed_error("Illegal public flags value.");
2301 return false;
2302 }
2303
2304 if (header->reset_flag && header->version_flag) {
2305 set_detailed_error("Got version flag in reset packet");
2306 return false;
2307 }
2308
2309 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2310 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
2311 if (!reader->ReadConnectionId(&header->destination_connection_id,
2312 kQuicDefaultConnectionIdLength)) {
2313 set_detailed_error("Unable to read ConnectionId.");
2314 return false;
2315 }
2316 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2317 break;
2318 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
2319 header->destination_connection_id_included = CONNECTION_ID_ABSENT;
2320 header->destination_connection_id = last_serialized_connection_id_;
2321 break;
2322 }
2323
2324 header->packet_number_length = ReadSequenceNumberLength(
2325 public_flags >> kPublicHeaderSequenceNumberShift);
2326
2327 // Read the version only if the packet is from the client.
2328 // version flag from the server means version negotiation packet.
2329 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2330 QuicVersionLabel version_label;
2331 if (!reader->ReadTag(&version_label)) {
2332 set_detailed_error("Unable to read protocol version.");
2333 return false;
2334 }
2335 // TODO(rch): Use ReadUInt32() once QUIC_VERSION_35 is removed.
2336 version_label = QuicEndian::NetToHost32(version_label);
2337
2338 // If the version from the new packet is the same as the version of this
2339 // framer, then the public flags should be set to something we understand.
2340 // If not, this raises an error.
2341 last_version_label_ = version_label;
2342 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2343 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2344 set_detailed_error("Illegal public flags value.");
2345 return false;
2346 }
2347 header->version = version;
2348 }
2349
2350 // A nonce should only be present in packets from the server to the client,
2351 // which are neither version negotiation nor public reset packets.
2352 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2353 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2354 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2355 // The nonce flag from a client is ignored and is assumed to be an older
2356 // client indicating an eight-byte connection ID.
2357 perspective_ == Perspective::IS_CLIENT) {
2358 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2359 last_nonce_.size())) {
2360 set_detailed_error("Unable to read nonce.");
2361 return false;
2362 }
2363 header->nonce = &last_nonce_;
2364 } else {
2365 header->nonce = nullptr;
2366 }
2367
2368 return true;
2369}
2370
2371// static
2372QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
2373 QuicTransportVersion version,
2374 QuicPacketNumber packet_number) {
2375 DCHECK(packet_number.IsInitialized());
2376 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2377 return PACKET_1BYTE_PACKET_NUMBER;
2378 } else if (packet_number <
2379 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2380 return PACKET_2BYTE_PACKET_NUMBER;
2381 } else if (packet_number <
2382 QuicPacketNumber(UINT64_C(1)
2383 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2384 return PACKET_4BYTE_PACKET_NUMBER;
2385 } else {
2386 return PACKET_6BYTE_PACKET_NUMBER;
2387 }
2388}
2389
2390// static
2391uint8_t QuicFramer::GetPacketNumberFlags(
2392 QuicPacketNumberLength packet_number_length) {
2393 switch (packet_number_length) {
2394 case PACKET_1BYTE_PACKET_NUMBER:
2395 return PACKET_FLAGS_1BYTE_PACKET;
2396 case PACKET_2BYTE_PACKET_NUMBER:
2397 return PACKET_FLAGS_2BYTE_PACKET;
2398 case PACKET_4BYTE_PACKET_NUMBER:
2399 return PACKET_FLAGS_4BYTE_PACKET;
2400 case PACKET_6BYTE_PACKET_NUMBER:
2401 case PACKET_8BYTE_PACKET_NUMBER:
2402 return PACKET_FLAGS_8BYTE_PACKET;
2403 default:
2404 QUIC_BUG << "Unreachable case statement.";
2405 return PACKET_FLAGS_8BYTE_PACKET;
2406 }
2407}
2408
2409// static
2410QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2411 const QuicAckFrame& frame) {
2412 AckFrameInfo new_ack_info;
2413 if (frame.packets.Empty()) {
2414 return new_ack_info;
2415 }
2416 // The first block is the last interval. It isn't encoded with the gap-length
2417 // encoding, so skip it.
2418 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2419 auto itr = frame.packets.rbegin();
2420 QuicPacketNumber previous_start = itr->min();
2421 new_ack_info.max_block_length = PacketNumberIntervalLength(*itr);
2422 ++itr;
2423
2424 // Don't do any more work after getting information for 256 ACK blocks; any
2425 // more can't be encoded anyway.
2426 for (; itr != frame.packets.rend() &&
2427 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2428 previous_start = itr->min(), ++itr) {
2429 const auto& interval = *itr;
2430 const QuicPacketCount total_gap = previous_start - interval.max();
2431 new_ack_info.num_ack_blocks +=
2432 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2433 std::numeric_limits<uint8_t>::max();
2434 new_ack_info.max_block_length = std::max(
2435 new_ack_info.max_block_length, PacketNumberIntervalLength(interval));
2436 }
2437 return new_ack_info;
2438}
2439
2440bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2441 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002442 QuicPacketNumber base_packet_number;
2443 if (supports_multiple_packet_number_spaces_) {
2444 base_packet_number =
2445 largest_decrypted_packet_numbers_[GetPacketNumberSpace(*header)];
2446 } else {
2447 base_packet_number = largest_packet_number_;
2448 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002449 uint64_t full_packet_number;
2450 if (!ProcessAndCalculatePacketNumber(
2451 encrypted_reader, header->packet_number_length, base_packet_number,
2452 &full_packet_number)) {
2453 set_detailed_error("Unable to read packet number.");
2454 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2455 }
2456
2457 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2458 set_detailed_error("packet numbers cannot be 0.");
2459 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2460 }
2461 header->packet_number = QuicPacketNumber(full_packet_number);
2462
2463 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2464 set_detailed_error(
2465 "Visitor asked to stop processing of unauthenticated header.");
2466 return false;
2467 }
2468 return true;
2469}
2470
2471bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2472 QuicPacketHeader* header) {
2473 uint8_t type;
2474 if (!reader->ReadBytes(&type, 1)) {
2475 set_detailed_error("Unable to read type.");
2476 return false;
2477 }
2478 // Determine whether this is a long or short header.
2479 header->form = type & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
2480 : IETF_QUIC_SHORT_HEADER_PACKET;
2481 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2482 // Version is always present in long headers.
2483 header->version_flag = true;
2484 // Long header packets received by client must include 8-byte source
2485 // connection ID, and those received by server must include 8-byte
2486 // destination connection ID.
2487 header->destination_connection_id_included =
2488 perspective_ == Perspective::IS_CLIENT ? CONNECTION_ID_ABSENT
2489 : CONNECTION_ID_PRESENT;
2490 header->source_connection_id_included =
2491 perspective_ == Perspective::IS_CLIENT ? CONNECTION_ID_PRESENT
2492 : CONNECTION_ID_ABSENT;
2493 // Read version tag.
2494 QuicVersionLabel version_label;
2495 if (!reader->ReadTag(&version_label)) {
2496 set_detailed_error("Unable to read protocol version.");
2497 return false;
2498 }
2499 // TODO(rch): Use ReadUInt32() once QUIC_VERSION_35 is removed.
2500 version_label = QuicEndian::NetToHost32(version_label);
2501 if (!version_label) {
2502 // Version label is 0 indicating this is a version negotiation packet.
2503 header->long_packet_type = VERSION_NEGOTIATION;
2504 } else {
2505 header->version = ParseQuicVersionLabel(version_label);
2506 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
2507 if (header->version.transport_version > QUIC_VERSION_44 &&
2508 !(type & FLAGS_FIXED_BIT)) {
2509 set_detailed_error("Fixed bit is 0 in long header.");
2510 return false;
2511 }
2512 if (!GetLongHeaderType(header->version.transport_version, type,
2513 &header->long_packet_type)) {
2514 set_detailed_error("Illegal long header type value.");
2515 return false;
2516 }
nharper2ceb97c2019-04-19 11:38:59 -07002517 if (header->long_packet_type == RETRY &&
2518 (version().KnowsWhichDecrypterToUse() ||
2519 supports_multiple_packet_number_spaces_)) {
2520 set_detailed_error("Not yet supported IETF RETRY packet received.");
2521 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2522 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002523 header->packet_number_length = GetLongHeaderPacketNumberLength(
2524 header->version.transport_version, type);
2525 }
2526 }
2527 if (header->long_packet_type != VERSION_NEGOTIATION) {
2528 // Do not save version of version negotiation packet.
2529 last_version_label_ = version_label;
2530 }
2531
2532 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2533 << QuicUtils::QuicLongHeaderTypetoString(
2534 header->long_packet_type);
2535 return true;
2536 }
2537
2538 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2539 // Version is not present in short headers.
2540 header->version_flag = false;
2541 // Connection ID length depends on the perspective. Client does not expect
2542 // destination connection ID, and server expects destination connection ID.
2543 header->destination_connection_id_included =
2544 perspective_ == Perspective::IS_CLIENT ? CONNECTION_ID_ABSENT
2545 : CONNECTION_ID_PRESENT;
2546 header->source_connection_id_included = CONNECTION_ID_ABSENT;
2547 if (infer_packet_header_type_from_version_ &&
2548 transport_version() > QUIC_VERSION_44 && !(type & FLAGS_FIXED_BIT)) {
2549 set_detailed_error("Fixed bit is 0 in short header.");
2550 return false;
2551 }
2552 if (!GetShortHeaderPacketNumberLength(transport_version(), type,
2553 infer_packet_header_type_from_version_,
2554 &header->packet_number_length)) {
2555 set_detailed_error("Illegal short header type value.");
2556 return false;
2557 }
2558 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2559 return true;
2560}
2561
2562bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2563 QuicPacketHeader* header) {
2564 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2565 return false;
2566 }
2567
2568 uint8_t destination_connection_id_length =
2569 header->destination_connection_id_included == CONNECTION_ID_PRESENT
2570 ? expected_connection_id_length_
2571 : 0;
2572 uint8_t source_connection_id_length =
2573 header->source_connection_id_included == CONNECTION_ID_PRESENT
2574 ? expected_connection_id_length_
2575 : 0;
2576 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2577 // Read and validate connection ID length.
2578 uint8_t connection_id_lengths_byte;
2579 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2580 set_detailed_error("Unable to read ConnectionId length.");
2581 return false;
2582 }
2583 uint8_t dcil =
2584 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2585 if (dcil != 0) {
2586 dcil += kConnectionIdLengthAdjustment;
2587 }
QUICHE team4d9d6292019-03-11 14:25:33 -07002588 if (should_update_expected_connection_id_length_ &&
2589 expected_connection_id_length_ != dcil) {
2590 QUIC_DVLOG(1) << ENDPOINT << "Updating expected_connection_id_length: "
2591 << static_cast<int>(expected_connection_id_length_)
2592 << " -> " << static_cast<int>(dcil);
2593 expected_connection_id_length_ = dcil;
2594 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002595 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2596 if (scil != 0) {
2597 scil += kConnectionIdLengthAdjustment;
2598 }
QUICHE team4d9d6292019-03-11 14:25:33 -07002599 if ((dcil != destination_connection_id_length ||
2600 scil != source_connection_id_length) &&
QUICHE team8e2e4532019-03-14 14:37:56 -07002601 !should_update_expected_connection_id_length_ &&
2602 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2603 header->version.transport_version)) {
2604 // TODO(dschinazi): use the framer's version once the
2605 // OnProtocolVersionMismatch call is moved to before this is run.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002606 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2607 << ", scil: " << static_cast<uint32_t>(scil);
2608 set_detailed_error("Invalid ConnectionId length.");
2609 return false;
2610 }
2611 destination_connection_id_length = dcil;
2612 source_connection_id_length = scil;
2613 }
2614
QUICHE team0131a5b2019-03-20 15:23:27 -07002615 DCHECK_LE(destination_connection_id_length, kQuicMaxConnectionIdLength);
2616 DCHECK_LE(source_connection_id_length, kQuicMaxConnectionIdLength);
2617
QUICHE teama6ef0a62019-03-07 20:34:33 -05002618 // Read connection ID.
2619 if (!reader->ReadConnectionId(&header->destination_connection_id,
2620 destination_connection_id_length)) {
2621 set_detailed_error("Unable to read Destination ConnectionId.");
2622 return false;
2623 }
2624
2625 if (!reader->ReadConnectionId(&header->source_connection_id,
2626 source_connection_id_length)) {
2627 set_detailed_error("Unable to read Source ConnectionId.");
2628 return false;
2629 }
2630
2631 if (header->source_connection_id_included == CONNECTION_ID_PRESENT) {
2632 // Set destination connection ID to source connection ID.
2633 DCHECK_EQ(EmptyQuicConnectionId(), header->destination_connection_id);
2634 header->destination_connection_id = header->source_connection_id;
2635 } else if (header->destination_connection_id_included ==
2636 CONNECTION_ID_ABSENT) {
2637 header->destination_connection_id = last_serialized_connection_id_;
2638 }
2639
2640 return true;
2641}
2642
2643bool QuicFramer::ProcessAndCalculatePacketNumber(
2644 QuicDataReader* reader,
2645 QuicPacketNumberLength packet_number_length,
2646 QuicPacketNumber base_packet_number,
2647 uint64_t* packet_number) {
2648 uint64_t wire_packet_number;
2649 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2650 return false;
2651 }
2652
2653 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2654 // in case the first guess is incorrect.
2655 *packet_number = CalculatePacketNumberFromWire(
2656 packet_number_length, base_packet_number, wire_packet_number);
2657 return true;
2658}
2659
2660bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2661 const QuicPacketHeader& header) {
2662 DCHECK_NE(QUIC_VERSION_99, version_.transport_version)
2663 << "Version 99 negotiated, but not processing frames as version 99.";
2664 if (reader->IsDoneReading()) {
2665 set_detailed_error("Packet has no frames.");
2666 return RaiseError(QUIC_MISSING_PAYLOAD);
2667 }
2668 while (!reader->IsDoneReading()) {
2669 uint8_t frame_type;
2670 if (!reader->ReadBytes(&frame_type, 1)) {
2671 set_detailed_error("Unable to read frame type.");
2672 return RaiseError(QUIC_INVALID_FRAME_DATA);
2673 }
2674 const uint8_t special_mask = transport_version() <= QUIC_VERSION_44
2675 ? kQuicFrameTypeBrokenMask
2676 : kQuicFrameTypeSpecialMask;
2677 if (frame_type & special_mask) {
2678 // Stream Frame
2679 if (frame_type & kQuicFrameTypeStreamMask) {
2680 QuicStreamFrame frame;
2681 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2682 return RaiseError(QUIC_INVALID_STREAM_DATA);
2683 }
2684 if (!visitor_->OnStreamFrame(frame)) {
2685 QUIC_DVLOG(1) << ENDPOINT
2686 << "Visitor asked to stop further processing.";
2687 // Returning true since there was no parsing error.
2688 return true;
2689 }
2690 continue;
2691 }
2692
2693 // Ack Frame
2694 if (frame_type & kQuicFrameTypeAckMask) {
2695 if (!ProcessAckFrame(reader, frame_type)) {
2696 return RaiseError(QUIC_INVALID_ACK_DATA);
2697 }
2698 continue;
2699 }
2700
2701 // This was a special frame type that did not match any
2702 // of the known ones. Error.
2703 set_detailed_error("Illegal frame type.");
2704 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2705 << static_cast<int>(frame_type);
2706 return RaiseError(QUIC_INVALID_FRAME_DATA);
2707 }
2708
2709 switch (frame_type) {
2710 case PADDING_FRAME: {
2711 QuicPaddingFrame frame;
2712 ProcessPaddingFrame(reader, &frame);
2713 if (!visitor_->OnPaddingFrame(frame)) {
2714 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2715 // Returning true since there was no parsing error.
2716 return true;
2717 }
2718 continue;
2719 }
2720
2721 case RST_STREAM_FRAME: {
2722 QuicRstStreamFrame frame;
2723 if (!ProcessRstStreamFrame(reader, &frame)) {
2724 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2725 }
2726 if (!visitor_->OnRstStreamFrame(frame)) {
2727 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2728 // Returning true since there was no parsing error.
2729 return true;
2730 }
2731 continue;
2732 }
2733
2734 case CONNECTION_CLOSE_FRAME: {
2735 QuicConnectionCloseFrame frame;
2736 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2737 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2738 }
2739
2740 if (!visitor_->OnConnectionCloseFrame(frame)) {
2741 QUIC_DVLOG(1) << ENDPOINT
2742 << "Visitor asked to stop further processing.";
2743 // Returning true since there was no parsing error.
2744 return true;
2745 }
2746 continue;
2747 }
2748
2749 case GOAWAY_FRAME: {
2750 QuicGoAwayFrame goaway_frame;
2751 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2752 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2753 }
2754 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2755 QUIC_DVLOG(1) << ENDPOINT
2756 << "Visitor asked to stop further processing.";
2757 // Returning true since there was no parsing error.
2758 return true;
2759 }
2760 continue;
2761 }
2762
2763 case WINDOW_UPDATE_FRAME: {
2764 QuicWindowUpdateFrame window_update_frame;
2765 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2766 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2767 }
2768 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2769 QUIC_DVLOG(1) << ENDPOINT
2770 << "Visitor asked to stop further processing.";
2771 // Returning true since there was no parsing error.
2772 return true;
2773 }
2774 continue;
2775 }
2776
2777 case BLOCKED_FRAME: {
2778 QuicBlockedFrame blocked_frame;
2779 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2780 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2781 }
2782 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2783 QUIC_DVLOG(1) << ENDPOINT
2784 << "Visitor asked to stop further processing.";
2785 // Returning true since there was no parsing error.
2786 return true;
2787 }
2788 continue;
2789 }
2790
2791 case STOP_WAITING_FRAME: {
2792 QuicStopWaitingFrame stop_waiting_frame;
2793 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2794 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2795 }
2796 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2797 QUIC_DVLOG(1) << ENDPOINT
2798 << "Visitor asked to stop further processing.";
2799 // Returning true since there was no parsing error.
2800 return true;
2801 }
2802 continue;
2803 }
2804 case PING_FRAME: {
2805 // Ping has no payload.
2806 QuicPingFrame ping_frame;
2807 if (!visitor_->OnPingFrame(ping_frame)) {
2808 QUIC_DVLOG(1) << ENDPOINT
2809 << "Visitor asked to stop further processing.";
2810 // Returning true since there was no parsing error.
2811 return true;
2812 }
2813 continue;
2814 }
2815 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2816 QUIC_FALLTHROUGH_INTENDED;
2817 case IETF_EXTENSION_MESSAGE: {
2818 QuicMessageFrame message_frame;
2819 if (!ProcessMessageFrame(reader,
2820 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2821 &message_frame)) {
2822 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2823 }
2824 if (!visitor_->OnMessageFrame(message_frame)) {
2825 QUIC_DVLOG(1) << ENDPOINT
2826 << "Visitor asked to stop further processing.";
2827 // Returning true since there was no parsing error.
2828 return true;
2829 }
2830 break;
2831 }
2832 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07002833 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002834 set_detailed_error("Illegal frame type.");
2835 return RaiseError(QUIC_INVALID_FRAME_DATA);
2836 }
2837 QuicCryptoFrame frame;
2838 if (!ProcessCryptoFrame(reader, &frame)) {
2839 return RaiseError(QUIC_INVALID_FRAME_DATA);
2840 }
2841 if (!visitor_->OnCryptoFrame(frame)) {
2842 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2843 // Returning true since there was no parsing error.
2844 return true;
2845 }
2846 break;
2847 }
2848
2849 default:
2850 set_detailed_error("Illegal frame type.");
2851 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2852 << static_cast<int>(frame_type);
2853 return RaiseError(QUIC_INVALID_FRAME_DATA);
2854 }
2855 }
2856
2857 return true;
2858}
2859
2860bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
2861 const QuicPacketHeader& header) {
2862 DCHECK_EQ(QUIC_VERSION_99, version_.transport_version)
2863 << "Attempt to process frames as IETF frames but version is "
2864 << version_.transport_version << ", not 99.";
2865 if (reader->IsDoneReading()) {
2866 set_detailed_error("Packet has no frames.");
2867 return RaiseError(QUIC_MISSING_PAYLOAD);
2868 }
2869 while (!reader->IsDoneReading()) {
2870 uint64_t frame_type;
2871 // Will be the number of bytes into which frame_type was encoded.
2872 size_t encoded_bytes = reader->BytesRemaining();
2873 if (!reader->ReadVarInt62(&frame_type)) {
2874 set_detailed_error("Unable to read frame type.");
2875 return RaiseError(QUIC_INVALID_FRAME_DATA);
2876 }
2877
2878 // Is now the number of bytes into which the frame type was encoded.
2879 encoded_bytes -= reader->BytesRemaining();
2880
2881 // Check that the frame type is minimally encoded.
2882 if (encoded_bytes !=
2883 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
2884 // The frame type was not minimally encoded.
2885 set_detailed_error("Frame type not minimally encoded.");
2886 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
2887 }
2888
2889 if (IS_IETF_STREAM_FRAME(frame_type)) {
2890 QuicStreamFrame frame;
2891 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
2892 return RaiseError(QUIC_INVALID_STREAM_DATA);
2893 }
2894 if (!visitor_->OnStreamFrame(frame)) {
2895 QUIC_DVLOG(1) << ENDPOINT
2896 << "Visitor asked to stop further processing.";
2897 // Returning true since there was no parsing error.
2898 return true;
2899 }
2900 } else {
2901 switch (frame_type) {
2902 case IETF_PADDING: {
2903 QuicPaddingFrame frame;
2904 ProcessPaddingFrame(reader, &frame);
2905 if (!visitor_->OnPaddingFrame(frame)) {
2906 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2907 // Returning true since there was no parsing error.
2908 return true;
2909 }
2910 break;
2911 }
2912 case IETF_RST_STREAM: {
2913 QuicRstStreamFrame frame;
2914 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
2915 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2916 }
2917 if (!visitor_->OnRstStreamFrame(frame)) {
2918 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2919 // Returning true since there was no parsing error.
2920 return true;
2921 }
2922 break;
2923 }
fkastenholz04bd4f32019-04-16 12:24:38 -07002924 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05002925 case IETF_CONNECTION_CLOSE: {
2926 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07002927 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07002928 reader,
2929 (frame_type == IETF_CONNECTION_CLOSE)
2930 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
2931 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
2932 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002933 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2934 }
2935 if (!visitor_->OnConnectionCloseFrame(frame)) {
2936 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2937 // Returning true since there was no parsing error.
2938 return true;
2939 }
2940 break;
2941 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002942 case IETF_MAX_DATA: {
2943 QuicWindowUpdateFrame frame;
2944 if (!ProcessMaxDataFrame(reader, &frame)) {
2945 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
2946 }
2947 // TODO(fkastenholz): Or should we create a new visitor function,
2948 // OnMaxDataFrame()?
2949 if (!visitor_->OnWindowUpdateFrame(frame)) {
2950 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2951 // Returning true since there was no parsing error.
2952 return true;
2953 }
2954 break;
2955 }
2956 case IETF_MAX_STREAM_DATA: {
2957 QuicWindowUpdateFrame frame;
2958 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
2959 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
2960 }
2961 // TODO(fkastenholz): Or should we create a new visitor function,
2962 // OnMaxStreamDataFrame()?
2963 if (!visitor_->OnWindowUpdateFrame(frame)) {
2964 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2965 // Returning true since there was no parsing error.
2966 return true;
2967 }
2968 break;
2969 }
2970 case IETF_MAX_STREAMS_BIDIRECTIONAL:
2971 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
2972 QuicMaxStreamIdFrame frame;
2973 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
2974 return RaiseError(QUIC_MAX_STREAM_ID_DATA);
2975 }
2976 QUIC_CODE_COUNT_N(max_stream_id_received, 1, 2);
2977 if (!visitor_->OnMaxStreamIdFrame(frame)) {
2978 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2979 // Returning true since there was no parsing error.
2980 return true;
2981 }
2982 break;
2983 }
2984 case IETF_PING: {
2985 // Ping has no payload.
2986 QuicPingFrame ping_frame;
2987 if (!visitor_->OnPingFrame(ping_frame)) {
2988 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2989 // Returning true since there was no parsing error.
2990 return true;
2991 }
2992 break;
2993 }
2994 case IETF_BLOCKED: {
2995 QuicBlockedFrame frame;
2996 if (!ProcessIetfBlockedFrame(reader, &frame)) {
2997 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2998 }
2999 if (!visitor_->OnBlockedFrame(frame)) {
3000 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3001 // Returning true since there was no parsing error.
3002 return true;
3003 }
3004 break;
3005 }
3006 case IETF_STREAM_BLOCKED: {
3007 QuicBlockedFrame frame;
3008 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3009 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3010 }
3011 if (!visitor_->OnBlockedFrame(frame)) {
3012 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3013 // Returning true since there was no parsing error.
3014 return true;
3015 }
3016 break;
3017 }
3018 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3019 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
3020 QuicStreamIdBlockedFrame frame;
3021 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
3022 return RaiseError(QUIC_STREAM_ID_BLOCKED_DATA);
3023 }
3024 QUIC_CODE_COUNT_N(stream_id_blocked_received, 1, 2);
3025 if (!visitor_->OnStreamIdBlockedFrame(frame)) {
3026 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3027 // Returning true since there was no parsing error.
3028 return true;
3029 }
3030 break;
3031 }
3032 case IETF_NEW_CONNECTION_ID: {
3033 QuicNewConnectionIdFrame frame;
3034 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3035 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3036 }
3037 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3038 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3039 // Returning true since there was no parsing error.
3040 return true;
3041 }
3042 break;
3043 }
3044 case IETF_RETIRE_CONNECTION_ID: {
3045 QuicRetireConnectionIdFrame frame;
3046 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3047 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3048 }
3049 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3050 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3051 // Returning true since there was no parsing error.
3052 return true;
3053 }
3054 break;
3055 }
3056 case IETF_NEW_TOKEN: {
3057 QuicNewTokenFrame frame;
3058 if (!ProcessNewTokenFrame(reader, &frame)) {
3059 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3060 }
3061 if (!visitor_->OnNewTokenFrame(frame)) {
3062 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3063 // Returning true since there was no parsing error.
3064 return true;
3065 }
3066 break;
3067 }
3068 case IETF_STOP_SENDING: {
3069 QuicStopSendingFrame frame;
3070 if (!ProcessStopSendingFrame(reader, &frame)) {
3071 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3072 }
3073 if (!visitor_->OnStopSendingFrame(frame)) {
3074 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3075 // Returning true since there was no parsing error.
3076 return true;
3077 }
3078 break;
3079 }
3080 case IETF_ACK_ECN:
3081 case IETF_ACK: {
3082 QuicAckFrame frame;
3083 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3084 return RaiseError(QUIC_INVALID_ACK_DATA);
3085 }
3086 break;
3087 }
3088 case IETF_PATH_CHALLENGE: {
3089 QuicPathChallengeFrame frame;
3090 if (!ProcessPathChallengeFrame(reader, &frame)) {
3091 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3092 }
3093 if (!visitor_->OnPathChallengeFrame(frame)) {
3094 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3095 // Returning true since there was no parsing error.
3096 return true;
3097 }
3098 break;
3099 }
3100 case IETF_PATH_RESPONSE: {
3101 QuicPathResponseFrame frame;
3102 if (!ProcessPathResponseFrame(reader, &frame)) {
3103 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3104 }
3105 if (!visitor_->OnPathResponseFrame(frame)) {
3106 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3107 // Returning true since there was no parsing error.
3108 return true;
3109 }
3110 break;
3111 }
3112 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3113 QUIC_FALLTHROUGH_INTENDED;
3114 case IETF_EXTENSION_MESSAGE: {
3115 QuicMessageFrame message_frame;
3116 if (!ProcessMessageFrame(
3117 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3118 &message_frame)) {
3119 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3120 }
3121 if (!visitor_->OnMessageFrame(message_frame)) {
3122 QUIC_DVLOG(1) << ENDPOINT
3123 << "Visitor asked to stop further processing.";
3124 // Returning true since there was no parsing error.
3125 return true;
3126 }
3127 break;
3128 }
3129 case IETF_CRYPTO: {
3130 QuicCryptoFrame frame;
3131 if (!ProcessCryptoFrame(reader, &frame)) {
3132 return RaiseError(QUIC_INVALID_FRAME_DATA);
3133 }
3134 if (!visitor_->OnCryptoFrame(frame)) {
3135 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3136 // Returning true since there was no parsing error.
3137 return true;
3138 }
3139 break;
3140 }
3141
3142 default:
3143 set_detailed_error("Illegal frame type.");
3144 QUIC_DLOG(WARNING)
3145 << ENDPOINT
3146 << "Illegal frame type: " << static_cast<int>(frame_type);
3147 return RaiseError(QUIC_INVALID_FRAME_DATA);
3148 }
3149 }
3150 }
3151 return true;
3152}
3153
3154namespace {
3155// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3156inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3157 return (1u << num_bits) - 1;
3158}
3159
3160// Extract |num_bits| from |flags| offset by |offset|.
3161uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3162 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3163}
3164
3165// Extract the bit at position |offset| from |flags| as a bool.
3166bool ExtractBit(uint8_t flags, uint8_t offset) {
3167 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3168}
3169
3170// Set |num_bits|, offset by |offset| to |val| in |flags|.
3171void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3172 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3173 *flags |= val << offset;
3174}
3175
3176// Set the bit at position |offset| to |val| in |flags|.
3177void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3178 SetBits(flags, val ? 1 : 0, 1, offset);
3179}
3180} // namespace
3181
3182bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3183 uint8_t frame_type,
3184 QuicStreamFrame* frame) {
3185 uint8_t stream_flags = frame_type;
3186
3187 uint8_t stream_id_length = 0;
3188 uint8_t offset_length = 4;
3189 bool has_data_length = true;
3190 stream_flags &= ~kQuicFrameTypeStreamMask;
3191
3192 // Read from right to left: StreamID, Offset, Data Length, Fin.
3193 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3194 stream_flags >>= kQuicStreamIdShift;
3195
3196 offset_length = (stream_flags & kQuicStreamOffsetMask);
3197 // There is no encoding for 1 byte, only 0 and 2 through 8.
3198 if (offset_length > 0) {
3199 offset_length += 1;
3200 }
3201 stream_flags >>= kQuicStreamShift;
3202
3203 has_data_length =
3204 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3205 stream_flags >>= kQuicStreamDataLengthShift;
3206
3207 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3208
3209 uint64_t stream_id;
3210 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3211 set_detailed_error("Unable to read stream_id.");
3212 return false;
3213 }
3214 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3215
3216 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3217 set_detailed_error("Unable to read offset.");
3218 return false;
3219 }
3220
3221 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3222 QuicStringPiece data;
3223 if (has_data_length) {
3224 if (!reader->ReadStringPiece16(&data)) {
3225 set_detailed_error("Unable to read frame data.");
3226 return false;
3227 }
3228 } else {
3229 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3230 set_detailed_error("Unable to read frame data.");
3231 return false;
3232 }
3233 }
3234 frame->data_buffer = data.data();
3235 frame->data_length = static_cast<uint16_t>(data.length());
3236
3237 return true;
3238}
3239
3240bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3241 uint8_t frame_type,
3242 QuicStreamFrame* frame) {
3243 // Read stream id from the frame. It's always present.
3244 if (!reader->ReadVarIntStreamId(&frame->stream_id)) {
3245 set_detailed_error("Unable to read stream_id.");
3246 return false;
3247 }
3248
3249 // If we have a data offset, read it. If not, set to 0.
3250 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3251 if (!reader->ReadVarInt62(&frame->offset)) {
3252 set_detailed_error("Unable to read stream data offset.");
3253 return false;
3254 }
3255 } else {
3256 // no offset in the frame, ensure it's 0 in the Frame.
3257 frame->offset = 0;
3258 }
3259
3260 // If we have a data length, read it. If not, set to 0.
3261 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3262 QuicIetfStreamDataLength length;
3263 if (!reader->ReadVarInt62(&length)) {
3264 set_detailed_error("Unable to read stream data length.");
3265 return false;
3266 }
3267 if (length > 0xffff) {
3268 set_detailed_error("Stream data length is too large.");
3269 return false;
3270 }
3271 frame->data_length = length;
3272 } else {
3273 // no length in the frame, it is the number of bytes remaining in the
3274 // packet.
3275 frame->data_length = reader->BytesRemaining();
3276 }
3277
3278 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3279 frame->fin = true;
3280 } else {
3281 frame->fin = false;
3282 }
3283
3284 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3285 QuicStringPiece data;
3286 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3287 set_detailed_error("Unable to read frame data.");
3288 return false;
3289 }
3290 frame->data_buffer = data.data();
3291 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3292
3293 return true;
3294}
3295
3296bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3297 QuicCryptoFrame* frame) {
3298 if (!reader->ReadVarInt62(&frame->offset)) {
3299 set_detailed_error("Unable to read crypto data offset.");
3300 return false;
3301 }
3302 uint64_t len;
3303 if (!reader->ReadVarInt62(&len) ||
3304 len > std::numeric_limits<QuicPacketLength>::max()) {
3305 set_detailed_error("Invalid data length.");
3306 return false;
3307 }
3308 frame->data_length = len;
3309
3310 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3311 QuicStringPiece data;
3312 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3313 set_detailed_error("Unable to read frame data.");
3314 return false;
3315 }
3316 frame->data_buffer = data.data();
3317 return true;
3318}
3319
3320bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3321 const bool has_ack_blocks =
3322 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3323 uint8_t num_ack_blocks = 0;
3324 uint8_t num_received_packets = 0;
3325
3326 // Determine the two lengths from the frame type: largest acked length,
3327 // ack block length.
3328 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
3329 version_.transport_version,
3330 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3331 kActBlockLengthOffset));
3332 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
3333 version_.transport_version,
3334 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3335 kLargestAckedOffset));
3336
3337 uint64_t largest_acked;
3338 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3339 set_detailed_error("Unable to read largest acked.");
3340 return false;
3341 }
3342
3343 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3344 // Connection always sends packet starting from kFirstSendingPacketNumber >
3345 // 0, peer has observed an unsent packet.
3346 set_detailed_error("Largest acked is 0.");
3347 return false;
3348 }
3349
3350 uint64_t ack_delay_time_us;
3351 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3352 set_detailed_error("Unable to read ack delay time.");
3353 return false;
3354 }
3355
3356 if (!visitor_->OnAckFrameStart(
3357 QuicPacketNumber(largest_acked),
3358 ack_delay_time_us == kUFloat16MaxValue
3359 ? QuicTime::Delta::Infinite()
3360 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3361 // The visitor suppresses further processing of the packet. Although this is
3362 // not a parsing error, returns false as this is in middle of processing an
3363 // ack frame,
3364 set_detailed_error("Visitor suppresses further processing of ack frame.");
3365 return false;
3366 }
3367
3368 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3369 set_detailed_error("Unable to read num of ack blocks.");
3370 return false;
3371 }
3372
3373 uint64_t first_block_length;
3374 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3375 set_detailed_error("Unable to read first ack block length.");
3376 return false;
3377 }
3378
3379 if (first_block_length == 0) {
3380 set_detailed_error("First block length is zero.");
3381 return false;
3382 }
3383 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3384 if (first_block_length + first_sending_packet_number_.ToUint64() >
3385 largest_acked + 1) {
3386 first_ack_block_underflow = true;
3387 }
3388 if (first_ack_block_underflow) {
3389 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3390 first_block_length, " largest acked is ",
3391 largest_acked, ".")
3392 .c_str());
3393 return false;
3394 }
3395
3396 uint64_t first_received = largest_acked + 1 - first_block_length;
3397 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3398 QuicPacketNumber(largest_acked + 1))) {
3399 // The visitor suppresses further processing of the packet. Although
3400 // this is not a parsing error, returns false as this is in middle
3401 // of processing an ack frame,
3402 set_detailed_error("Visitor suppresses further processing of ack frame.");
3403 return false;
3404 }
3405
3406 if (num_ack_blocks > 0) {
3407 for (size_t i = 0; i < num_ack_blocks; ++i) {
3408 uint8_t gap = 0;
3409 if (!reader->ReadUInt8(&gap)) {
3410 set_detailed_error("Unable to read gap to next ack block.");
3411 return false;
3412 }
3413 uint64_t current_block_length;
3414 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3415 set_detailed_error("Unable to ack block length.");
3416 return false;
3417 }
3418 bool ack_block_underflow = first_received < gap + current_block_length;
3419 if (first_received < gap + current_block_length +
3420 first_sending_packet_number_.ToUint64()) {
3421 ack_block_underflow = true;
3422 }
3423 if (ack_block_underflow) {
3424 set_detailed_error(
3425 QuicStrCat("Underflow with ack block length ", current_block_length,
3426 ", end of block is ", first_received - gap, ".")
3427 .c_str());
3428 return false;
3429 }
3430
3431 first_received -= (gap + current_block_length);
3432 if (current_block_length > 0) {
3433 if (!visitor_->OnAckRange(
3434 QuicPacketNumber(first_received),
3435 QuicPacketNumber(first_received) + current_block_length)) {
3436 // The visitor suppresses further processing of the packet. Although
3437 // this is not a parsing error, returns false as this is in middle
3438 // of processing an ack frame,
3439 set_detailed_error(
3440 "Visitor suppresses further processing of ack frame.");
3441 return false;
3442 }
3443 }
3444 }
3445 }
3446
3447 if (!reader->ReadUInt8(&num_received_packets)) {
3448 set_detailed_error("Unable to read num received packets.");
3449 return false;
3450 }
3451
3452 if (!ProcessTimestampsInAckFrame(num_received_packets,
3453 QuicPacketNumber(largest_acked), reader)) {
3454 return false;
3455 }
3456
3457 // Done processing the ACK frame.
3458 return visitor_->OnAckFrameEnd(QuicPacketNumber(first_received));
3459}
3460
3461bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3462 QuicPacketNumber largest_acked,
3463 QuicDataReader* reader) {
3464 if (num_received_packets == 0) {
3465 return true;
3466 }
3467 uint8_t delta_from_largest_observed;
3468 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3469 set_detailed_error("Unable to read sequence delta in received packets.");
3470 return false;
3471 }
3472
3473 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3474 set_detailed_error(QuicStrCat("delta_from_largest_observed too high: ",
3475 delta_from_largest_observed,
3476 ", largest_acked: ", largest_acked.ToUint64())
3477 .c_str());
3478 return false;
3479 }
3480
3481 // Time delta from the framer creation.
3482 uint32_t time_delta_us;
3483 if (!reader->ReadUInt32(&time_delta_us)) {
3484 set_detailed_error("Unable to read time delta in received packets.");
3485 return false;
3486 }
3487
3488 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3489 if (process_timestamps_) {
3490 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3491
3492 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3493 }
3494
3495 for (uint8_t i = 1; i < num_received_packets; ++i) {
3496 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3497 set_detailed_error("Unable to read sequence delta in received packets.");
3498 return false;
3499 }
3500 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3501 set_detailed_error(
3502 QuicStrCat("delta_from_largest_observed too high: ",
3503 delta_from_largest_observed,
3504 ", largest_acked: ", largest_acked.ToUint64())
3505 .c_str());
3506 return false;
3507 }
3508 seq_num = largest_acked - delta_from_largest_observed;
3509
3510 // Time delta from the previous timestamp.
3511 uint64_t incremental_time_delta_us;
3512 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3513 set_detailed_error(
3514 "Unable to read incremental time delta in received packets.");
3515 return false;
3516 }
3517
3518 if (process_timestamps_) {
3519 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3520 incremental_time_delta_us);
3521 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3522 }
3523 }
3524 return true;
3525}
3526
3527bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3528 uint64_t frame_type,
3529 QuicAckFrame* ack_frame) {
3530 uint64_t largest_acked;
3531 if (!reader->ReadVarInt62(&largest_acked)) {
3532 set_detailed_error("Unable to read largest acked.");
3533 return false;
3534 }
3535 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3536 // Connection always sends packet starting from kFirstSendingPacketNumber >
3537 // 0, peer has observed an unsent packet.
3538 set_detailed_error("Largest acked is 0.");
3539 return false;
3540 }
3541 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3542 uint64_t ack_delay_time_in_us;
3543 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3544 set_detailed_error("Unable to read ack delay time.");
3545 return false;
3546 }
3547
3548 // TODO(fkastenholz) when we get real IETF QUIC, need to get
3549 // the currect shift from the transport parameters.
3550 if (ack_delay_time_in_us == kVarInt62MaxValue) {
3551 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3552 } else {
3553 ack_delay_time_in_us = (ack_delay_time_in_us << kIetfAckTimestampShift);
3554 ack_frame->ack_delay_time =
3555 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3556 }
3557 if (frame_type == IETF_ACK_ECN) {
3558 ack_frame->ecn_counters_populated = true;
3559 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3560 set_detailed_error("Unable to read ack ect_0_count.");
3561 return false;
3562 }
3563 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3564 set_detailed_error("Unable to read ack ect_1_count.");
3565 return false;
3566 }
3567 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3568 set_detailed_error("Unable to read ack ecn_ce_count.");
3569 return false;
3570 }
3571 } else {
3572 ack_frame->ecn_counters_populated = false;
3573 ack_frame->ect_0_count = 0;
3574 ack_frame->ect_1_count = 0;
3575 ack_frame->ecn_ce_count = 0;
3576 }
3577 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3578 ack_frame->ack_delay_time)) {
3579 // The visitor suppresses further processing of the packet. Although this is
3580 // not a parsing error, returns false as this is in middle of processing an
3581 // ACK frame.
3582 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3583 return false;
3584 }
3585
3586 // Get number of ACK blocks from the packet.
3587 uint64_t ack_block_count;
3588 if (!reader->ReadVarInt62(&ack_block_count)) {
3589 set_detailed_error("Unable to read ack block count.");
3590 return false;
3591 }
3592 // There always is a first ACK block, which is the (number of packets being
3593 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3594 // value is 0, then only largest is acked. If it is 1, then largest-1,
3595 // largest] are acked, etc
3596 uint64_t ack_block_value;
3597 if (!reader->ReadVarInt62(&ack_block_value)) {
3598 set_detailed_error("Unable to read first ack block length.");
3599 return false;
3600 }
3601 // Calculate the packets being acked in the first block.
3602 // +1 because AddRange implementation requires [low,high)
3603 uint64_t block_high = largest_acked + 1;
3604 uint64_t block_low = largest_acked - ack_block_value;
3605
3606 // ack_block_value is the number of packets preceding the
3607 // largest_acked packet which are in the block being acked. Thus,
3608 // its maximum value is largest_acked-1. Test this, reporting an
3609 // error if the value is wrong.
3610 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3611 largest_acked) {
3612 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3613 ack_block_value + 1, " largest acked is ",
3614 largest_acked, ".")
3615 .c_str());
3616 return false;
3617 }
3618
3619 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3620 QuicPacketNumber(block_high))) {
3621 // The visitor suppresses further processing of the packet. Although
3622 // this is not a parsing error, returns false as this is in middle
3623 // of processing an ACK frame.
3624 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3625 return false;
3626 }
3627
3628 while (ack_block_count != 0) {
3629 uint64_t gap_block_value;
3630 // Get the sizes of the gap and ack blocks,
3631 if (!reader->ReadVarInt62(&gap_block_value)) {
3632 set_detailed_error("Unable to read gap block value.");
3633 return false;
3634 }
3635 // It's an error if the gap is larger than the space from packet
3636 // number 0 to the start of the block that's just been acked, PLUS
3637 // there must be space for at least 1 packet to be acked. For
3638 // example, if block_low is 10 and gap_block_value is 9, it means
3639 // the gap block is 10 packets long, leaving no room for a packet
3640 // to be acked. Thus, gap_block_value+2 can not be larger than
3641 // block_low.
3642 // The test is written this way to detect wrap-arounds.
3643 if ((gap_block_value + 2) > block_low) {
3644 set_detailed_error(
3645 QuicStrCat("Underflow with gap block length ", gap_block_value + 1,
3646 " previous ack block start is ", block_low, ".")
3647 .c_str());
3648 return false;
3649 }
3650
3651 // Adjust block_high to be the top of the next ack block.
3652 // There is a gap of |gap_block_value| packets between the bottom
3653 // of ack block N and top of block N+1. Note that gap_block_value
3654 // is he size of the gap minus 1 (per the QUIC protocol), and
3655 // block_high is the packet number of the first packet of the gap
3656 // (per the implementation of OnAckRange/AddAckRange, below).
3657 block_high = block_low - 1 - gap_block_value;
3658
3659 if (!reader->ReadVarInt62(&ack_block_value)) {
3660 set_detailed_error("Unable to read ack block value.");
3661 return false;
3662 }
3663 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3664 (block_high - 1)) {
3665 set_detailed_error(
3666 QuicStrCat("Underflow with ack block length ", ack_block_value + 1,
3667 " latest ack block end is ", block_high - 1, ".")
3668 .c_str());
3669 return false;
3670 }
3671 // Calculate the low end of the new nth ack block. The +1 is
3672 // because the encoded value is the blocksize-1.
3673 block_low = block_high - 1 - ack_block_value;
3674 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3675 QuicPacketNumber(block_high))) {
3676 // The visitor suppresses further processing of the packet. Although
3677 // this is not a parsing error, returns false as this is in middle
3678 // of processing an ACK frame.
3679 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3680 return false;
3681 }
3682
3683 // Another one done.
3684 ack_block_count--;
3685 }
3686
3687 return visitor_->OnAckFrameEnd(QuicPacketNumber(block_low));
3688}
3689
3690bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3691 const QuicPacketHeader& header,
3692 QuicStopWaitingFrame* stop_waiting) {
3693 uint64_t least_unacked_delta;
3694 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3695 &least_unacked_delta)) {
3696 set_detailed_error("Unable to read least unacked delta.");
3697 return false;
3698 }
3699 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3700 set_detailed_error("Invalid unacked delta.");
3701 return false;
3702 }
3703 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3704
3705 return true;
3706}
3707
3708bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3709 QuicRstStreamFrame* frame) {
3710 if (!reader->ReadUInt32(&frame->stream_id)) {
3711 set_detailed_error("Unable to read stream_id.");
3712 return false;
3713 }
3714
3715 if (!reader->ReadUInt64(&frame->byte_offset)) {
3716 set_detailed_error("Unable to read rst stream sent byte offset.");
3717 return false;
3718 }
3719
3720 uint32_t error_code;
3721 if (!reader->ReadUInt32(&error_code)) {
3722 set_detailed_error("Unable to read rst stream error code.");
3723 return false;
3724 }
3725
3726 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3727 // Ignore invalid stream error code if any.
3728 error_code = QUIC_STREAM_LAST_ERROR;
3729 }
3730
3731 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3732
3733 return true;
3734}
3735
3736bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3737 QuicConnectionCloseFrame* frame) {
3738 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003739 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3740
QUICHE teama6ef0a62019-03-07 20:34:33 -05003741 if (!reader->ReadUInt32(&error_code)) {
3742 set_detailed_error("Unable to read connection close error code.");
3743 return false;
3744 }
3745
3746 if (error_code >= QUIC_LAST_ERROR) {
3747 // Ignore invalid QUIC error code if any.
3748 error_code = QUIC_LAST_ERROR;
3749 }
3750
fkastenholze9d71a82019-04-09 05:12:13 -07003751 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003752
3753 QuicStringPiece error_details;
3754 if (!reader->ReadStringPiece16(&error_details)) {
3755 set_detailed_error("Unable to read connection close error details.");
3756 return false;
3757 }
vasilvvc48c8712019-03-11 13:38:16 -07003758 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003759
3760 return true;
3761}
3762
3763bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3764 QuicGoAwayFrame* frame) {
3765 uint32_t error_code;
3766 if (!reader->ReadUInt32(&error_code)) {
3767 set_detailed_error("Unable to read go away error code.");
3768 return false;
3769 }
3770
3771 if (error_code >= QUIC_LAST_ERROR) {
3772 // Ignore invalid QUIC error code if any.
3773 error_code = QUIC_LAST_ERROR;
3774 }
3775 frame->error_code = static_cast<QuicErrorCode>(error_code);
3776
3777 uint32_t stream_id;
3778 if (!reader->ReadUInt32(&stream_id)) {
3779 set_detailed_error("Unable to read last good stream id.");
3780 return false;
3781 }
3782 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
3783
3784 QuicStringPiece reason_phrase;
3785 if (!reader->ReadStringPiece16(&reason_phrase)) {
3786 set_detailed_error("Unable to read goaway reason.");
3787 return false;
3788 }
vasilvvc48c8712019-03-11 13:38:16 -07003789 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003790
3791 return true;
3792}
3793
3794bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
3795 QuicWindowUpdateFrame* frame) {
3796 if (!reader->ReadUInt32(&frame->stream_id)) {
3797 set_detailed_error("Unable to read stream_id.");
3798 return false;
3799 }
3800
3801 if (!reader->ReadUInt64(&frame->byte_offset)) {
3802 set_detailed_error("Unable to read window byte_offset.");
3803 return false;
3804 }
3805
3806 return true;
3807}
3808
3809bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
3810 QuicBlockedFrame* frame) {
3811 DCHECK_NE(QUIC_VERSION_99, version_.transport_version)
3812 << "Attempt to process non-IETF frames but version is 99";
3813
3814 if (!reader->ReadUInt32(&frame->stream_id)) {
3815 set_detailed_error("Unable to read stream_id.");
3816 return false;
3817 }
3818
3819 return true;
3820}
3821
3822void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
3823 QuicPaddingFrame* frame) {
3824 // Type byte has been read.
3825 frame->num_padding_bytes = 1;
3826 uint8_t next_byte;
3827 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
3828 reader->ReadBytes(&next_byte, 1);
3829 DCHECK_EQ(0x00, next_byte);
3830 ++frame->num_padding_bytes;
3831 }
3832}
3833
3834bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
3835 bool no_message_length,
3836 QuicMessageFrame* frame) {
3837 if (no_message_length) {
3838 QuicStringPiece remaining(reader->ReadRemainingPayload());
3839 frame->data = remaining.data();
3840 frame->message_length = remaining.length();
3841 return true;
3842 }
3843
3844 uint64_t message_length;
3845 if (!reader->ReadVarInt62(&message_length)) {
3846 set_detailed_error("Unable to read message length");
3847 return false;
3848 }
3849
3850 QuicStringPiece message_piece;
3851 if (!reader->ReadStringPiece(&message_piece, message_length)) {
3852 set_detailed_error("Unable to read message data");
3853 return false;
3854 }
3855
3856 frame->data = message_piece.data();
3857 frame->message_length = message_length;
3858
3859 return true;
3860}
3861
3862// static
3863QuicStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
3864 QuicTransportVersion version,
3865 const QuicEncryptedPacket& encrypted,
3866 QuicConnectionIdLength destination_connection_id_length,
3867 QuicConnectionIdLength source_connection_id_length,
3868 bool includes_version,
3869 bool includes_diversification_nonce,
3870 QuicPacketNumberLength packet_number_length,
3871 QuicVariableLengthIntegerLength retry_token_length_length,
3872 uint64_t retry_token_length,
3873 QuicVariableLengthIntegerLength length_length) {
3874 // TODO(ianswett): This is identical to QuicData::AssociatedData.
3875 return QuicStringPiece(
3876 encrypted.data(),
3877 GetStartOfEncryptedData(version, destination_connection_id_length,
3878 source_connection_id_length, includes_version,
3879 includes_diversification_nonce,
3880 packet_number_length, retry_token_length_length,
3881 retry_token_length, length_length));
3882}
3883
3884void QuicFramer::SetDecrypter(EncryptionLevel level,
3885 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07003886 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003887 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07003888 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07003889 decrypter_[decrypter_level_] = nullptr;
3890 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003891 decrypter_level_ = level;
3892}
3893
3894void QuicFramer::SetAlternativeDecrypter(
3895 EncryptionLevel level,
3896 std::unique_ptr<QuicDecrypter> decrypter,
3897 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07003898 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07003899 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07003900 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
3901 decrypter_[alternative_decrypter_level_] = nullptr;
3902 }
3903 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003904 alternative_decrypter_level_ = level;
3905 alternative_decrypter_latch_ = latch_once_used;
3906}
3907
zhongyi546cc452019-04-12 15:27:49 -07003908void QuicFramer::InstallDecrypter(EncryptionLevel level,
3909 std::unique_ptr<QuicDecrypter> decrypter) {
3910 DCHECK(version_.KnowsWhichDecrypterToUse());
3911 decrypter_[level] = std::move(decrypter);
3912}
3913
3914void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
3915 DCHECK(version_.KnowsWhichDecrypterToUse());
3916 decrypter_[level] = nullptr;
3917}
3918
3919const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
3920 DCHECK(version_.KnowsWhichDecrypterToUse());
3921 return decrypter_[level].get();
3922}
3923
QUICHE teama6ef0a62019-03-07 20:34:33 -05003924const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07003925 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003926}
3927
3928const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07003929 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
3930 return nullptr;
3931 }
3932 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003933}
3934
3935void QuicFramer::SetEncrypter(EncryptionLevel level,
3936 std::unique_ptr<QuicEncrypter> encrypter) {
3937 DCHECK_GE(level, 0);
3938 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
3939 encrypter_[level] = std::move(encrypter);
3940}
3941
3942size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
3943 QuicPacketNumber packet_number,
3944 size_t ad_len,
3945 size_t total_len,
3946 size_t buffer_len,
3947 char* buffer) {
3948 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07003949 if (encrypter_[level] == nullptr) {
3950 QUIC_BUG << ENDPOINT
3951 << "Attempted to encrypt in place without encrypter at level "
3952 << QuicUtils::EncryptionLevelToString(level);
3953 RaiseError(QUIC_ENCRYPTION_FAILURE);
3954 return 0;
3955 }
3956
QUICHE teama6ef0a62019-03-07 20:34:33 -05003957 size_t output_length = 0;
3958 if (!encrypter_[level]->EncryptPacket(
3959 packet_number.ToUint64(),
3960 QuicStringPiece(buffer, ad_len), // Associated data
3961 QuicStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext
3962 buffer + ad_len, // Destination buffer
3963 &output_length, buffer_len - ad_len)) {
3964 RaiseError(QUIC_ENCRYPTION_FAILURE);
3965 return 0;
3966 }
3967
3968 return ad_len + output_length;
3969}
3970
3971size_t QuicFramer::EncryptPayload(EncryptionLevel level,
3972 QuicPacketNumber packet_number,
3973 const QuicPacket& packet,
3974 char* buffer,
3975 size_t buffer_len) {
3976 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07003977 if (encrypter_[level] == nullptr) {
3978 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
3979 << QuicUtils::EncryptionLevelToString(level);
3980 RaiseError(QUIC_ENCRYPTION_FAILURE);
3981 return 0;
3982 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003983
3984 QuicStringPiece associated_data =
3985 packet.AssociatedData(version_.transport_version);
3986 // Copy in the header, because the encrypter only populates the encrypted
3987 // plaintext content.
3988 const size_t ad_len = associated_data.length();
3989 memmove(buffer, associated_data.data(), ad_len);
3990 // Encrypt the plaintext into the buffer.
3991 size_t output_length = 0;
3992 if (!encrypter_[level]->EncryptPacket(
3993 packet_number.ToUint64(), associated_data,
3994 packet.Plaintext(version_.transport_version), buffer + ad_len,
3995 &output_length, buffer_len - ad_len)) {
3996 RaiseError(QUIC_ENCRYPTION_FAILURE);
3997 return 0;
3998 }
3999
4000 return ad_len + output_length;
4001}
4002
4003size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4004 size_t plaintext_size) const {
4005 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4006}
4007
4008size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4009 // In order to keep the code simple, we don't have the current encryption
4010 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4011 size_t min_plaintext_size = ciphertext_size;
4012
QUICHE team6987b4a2019-03-15 16:23:04 -07004013 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004014 if (encrypter_[i] != nullptr) {
4015 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4016 if (size < min_plaintext_size) {
4017 min_plaintext_size = size;
4018 }
4019 }
4020 }
4021
4022 return min_plaintext_size;
4023}
4024
4025bool QuicFramer::DecryptPayload(QuicStringPiece encrypted,
4026 QuicStringPiece associated_data,
4027 const QuicPacketHeader& header,
4028 char* decrypted_buffer,
4029 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004030 size_t* decrypted_length,
4031 EncryptionLevel* decrypted_level) {
zhongyi546cc452019-04-12 15:27:49 -07004032 EncryptionLevel level = decrypter_level_;
4033 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004034 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004035 if (version().KnowsWhichDecrypterToUse()) {
4036 level = GetEncryptionLevel(header);
4037 decrypter = decrypter_[level].get();
4038 if (decrypter == nullptr) {
4039 return false;
4040 }
4041 if (level == ENCRYPTION_ZERO_RTT &&
4042 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4043 decrypter->SetDiversificationNonce(*header.nonce);
4044 }
4045 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
QUICHE team76086e42019-03-25 15:12:29 -07004046 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4047 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004048
zhongyi546cc452019-04-12 15:27:49 -07004049 DCHECK(decrypter != nullptr);
4050
4051 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004052 header.packet_number.ToUint64(), associated_data, encrypted,
4053 decrypted_buffer, decrypted_length, buffer_length);
4054 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004055 visitor_->OnDecryptedPacket(level);
4056 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004057 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004058 if (header.nonce != nullptr) {
4059 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004060 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004061 }
4062 bool try_alternative_decryption = true;
4063 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4064 if (perspective_ == Perspective::IS_CLIENT) {
4065 if (header.nonce == nullptr) {
4066 // Can not use INITIAL decryption without a diversification nonce.
4067 try_alternative_decryption = false;
4068 }
4069 } else {
4070 DCHECK(header.nonce == nullptr);
4071 }
4072 }
4073
4074 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004075 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004076 header.packet_number.ToUint64(), associated_data, encrypted,
4077 decrypted_buffer, decrypted_length, buffer_length);
4078 }
4079 if (success) {
4080 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004081 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004082 if (alternative_decrypter_latch_) {
4083 // Switch to the alternative decrypter and latch so that we cannot
4084 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004085 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004086 decrypter_[decrypter_level_] =
4087 std::move(decrypter_[alternative_decrypter_level_]);
4088 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004089 } else {
4090 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004091 EncryptionLevel level = alternative_decrypter_level_;
4092 alternative_decrypter_level_ = decrypter_level_;
4093 decrypter_level_ = level;
4094 }
4095 }
4096 }
4097
4098 if (!success) {
4099 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for packet_number:"
4100 << header.packet_number;
4101 return false;
4102 }
4103
4104 return true;
4105}
4106
4107size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4108 // Type byte, largest_acked, and delay_time are straight-forward.
4109 size_t ack_frame_size = kQuicFrameTypeSize;
4110 QuicPacketNumber largest_acked = LargestAcked(frame);
4111 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4112 uint64_t ack_delay_time_us;
4113 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
4114 ack_delay_time_us = ack_delay_time_us >> kIetfAckTimestampShift;
4115 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4116
4117 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4118 // then the ecn counters are included...
4119 if (frame.ecn_counters_populated &&
4120 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4121 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4122 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4123 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4124 }
4125
4126 // The rest (ack_block_count, first_ack_block, and additional ack
4127 // blocks, if any) depends:
4128 uint64_t ack_block_count = frame.packets.NumIntervals();
4129 if (ack_block_count == 0) {
4130 // If the QuicAckFrame has no Intervals, then it is interpreted
4131 // as an ack of a single packet at QuicAckFrame.largest_acked.
4132 // The resulting ack will consist of only the frame's
4133 // largest_ack & first_ack_block fields. The first ack block will be 0
4134 // (indicating a single packet) and the ack block_count will be 0.
4135 // Each 0 takes 1 byte when VarInt62 encoded.
4136 ack_frame_size += 2;
4137 return ack_frame_size;
4138 }
4139
4140 auto itr = frame.packets.rbegin();
4141 QuicPacketNumber ack_block_largest = largest_acked;
4142 QuicPacketNumber ack_block_smallest;
4143 if ((itr->max() - 1) == largest_acked) {
4144 // If largest_acked + 1 is equal to the Max() of the first Interval
4145 // in the QuicAckFrame then the first Interval is the first ack block of the
4146 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4147 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4148 // the remaining Intervals are encoded in additional ack blocks in the
4149 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4150 // Intervals - 1.
4151 ack_block_smallest = itr->min();
4152 itr++;
4153 ack_block_count--;
4154 } else {
4155 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4156 // the first Interval then it is interpreted as acking a single
4157 // packet at QuicAckFrame.largest_acked, with additional
4158 // Intervals indicating additional ack blocks. The encoding is
4159 // a) The packet's largest_acked is the QuicAckFrame's largest
4160 // acked,
4161 // b) the first ack block size is 0,
4162 // c) The packet's ack_block_count is the number of QuicAckFrame
4163 // Intervals, and
4164 // d) The QuicAckFrame Intervals are encoded in additional ack
4165 // blocks in the packet.
4166 ack_block_smallest = largest_acked;
4167 }
4168 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4169 ack_frame_size += ack_block_count_size;
4170
4171 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4172 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4173 ack_frame_size += first_ack_block_size;
4174
4175 // Account for the remaining Intervals, if any.
4176 while (ack_block_count != 0) {
4177 uint64_t gap_size = ack_block_smallest - itr->max();
4178 // Decrement per the protocol specification
4179 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4180 ack_frame_size += size_of_gap_size;
4181
4182 uint64_t block_size = itr->max() - itr->min();
4183 // Decrement per the protocol specification
4184 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4185 ack_frame_size += size_of_block_size;
4186
4187 ack_block_smallest = itr->min();
4188 itr++;
4189 ack_block_count--;
4190 }
4191
4192 return ack_frame_size;
4193}
4194
4195size_t QuicFramer::GetAckFrameSize(
4196 const QuicAckFrame& ack,
4197 QuicPacketNumberLength packet_number_length) {
4198 DCHECK(!ack.packets.Empty());
4199 size_t ack_size = 0;
4200
4201 if (version_.transport_version == QUIC_VERSION_99) {
4202 return GetIetfAckFrameSize(ack);
4203 }
4204 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4205 QuicPacketNumberLength largest_acked_length =
4206 GetMinPacketNumberLength(version_.transport_version, LargestAcked(ack));
4207 QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(
4208 version_.transport_version, QuicPacketNumber(ack_info.max_block_length));
4209
4210 ack_size =
4211 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4212 // First ack block length.
4213 ack_size += ack_block_length;
4214 if (ack_info.num_ack_blocks != 0) {
4215 ack_size += kNumberOfAckBlocksSize;
4216 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4217 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4218 }
4219
4220 // Include timestamps.
4221 if (process_timestamps_) {
4222 ack_size += GetAckFrameTimeStampSize(ack);
4223 }
4224
4225 return ack_size;
4226}
4227
4228size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4229 if (ack.received_packet_times.empty()) {
4230 return 0;
4231 }
4232
4233 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4234 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4235 (ack.received_packet_times.size() - 1);
4236}
4237
4238size_t QuicFramer::ComputeFrameLength(
4239 const QuicFrame& frame,
4240 bool last_frame_in_packet,
4241 QuicPacketNumberLength packet_number_length) {
4242 switch (frame.type) {
4243 case STREAM_FRAME:
4244 return GetMinStreamFrameSize(
4245 version_.transport_version, frame.stream_frame.stream_id,
4246 frame.stream_frame.offset, last_frame_in_packet,
4247 frame.stream_frame.data_length) +
4248 frame.stream_frame.data_length;
4249 case CRYPTO_FRAME:
4250 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4251 frame.crypto_frame->data_length) +
4252 frame.crypto_frame->data_length;
4253 case ACK_FRAME: {
4254 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4255 }
4256 case STOP_WAITING_FRAME:
4257 return GetStopWaitingFrameSize(version_.transport_version,
4258 packet_number_length);
4259 case MTU_DISCOVERY_FRAME:
4260 // MTU discovery frames are serialized as ping frames.
4261 return kQuicFrameTypeSize;
4262 case MESSAGE_FRAME:
4263 return GetMessageFrameSize(version_.transport_version,
4264 last_frame_in_packet,
4265 frame.message_frame->message_length);
4266 case PADDING_FRAME:
4267 DCHECK(false);
4268 return 0;
4269 default:
4270 return GetRetransmittableControlFrameSize(version_.transport_version,
4271 frame);
4272 }
4273}
4274
4275bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4276 bool last_frame_in_packet,
4277 QuicDataWriter* writer) {
4278 if (version_.transport_version == QUIC_VERSION_99) {
4279 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4280 }
4281 uint8_t type_byte = 0;
4282 switch (frame.type) {
4283 case STREAM_FRAME:
4284 type_byte =
4285 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4286 break;
4287 case ACK_FRAME:
4288 return true;
4289 case MTU_DISCOVERY_FRAME:
4290 type_byte = static_cast<uint8_t>(PING_FRAME);
4291 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004292 case NEW_CONNECTION_ID_FRAME:
4293 set_detailed_error(
4294 "Attempt to append NEW_CONNECTION_ID frame and not in version 99.");
4295 return RaiseError(QUIC_INTERNAL_ERROR);
4296 case RETIRE_CONNECTION_ID_FRAME:
4297 set_detailed_error(
4298 "Attempt to append RETIRE_CONNECTION_ID frame and not in version "
4299 "99.");
4300 return RaiseError(QUIC_INTERNAL_ERROR);
4301 case NEW_TOKEN_FRAME:
4302 set_detailed_error(
4303 "Attempt to append NEW_TOKEN frame and not in version 99.");
4304 return RaiseError(QUIC_INTERNAL_ERROR);
4305 case MAX_STREAM_ID_FRAME:
4306 set_detailed_error(
4307 "Attempt to append MAX_STREAM_ID frame and not in version 99.");
4308 return RaiseError(QUIC_INTERNAL_ERROR);
4309 case STREAM_ID_BLOCKED_FRAME:
4310 set_detailed_error(
4311 "Attempt to append STREAM_ID_BLOCKED frame and not in version 99.");
4312 return RaiseError(QUIC_INTERNAL_ERROR);
4313 case PATH_RESPONSE_FRAME:
4314 set_detailed_error(
4315 "Attempt to append PATH_RESPONSE frame and not in version 99.");
4316 return RaiseError(QUIC_INTERNAL_ERROR);
4317 case PATH_CHALLENGE_FRAME:
4318 set_detailed_error(
4319 "Attempt to append PATH_CHALLENGE frame and not in version 99.");
4320 return RaiseError(QUIC_INTERNAL_ERROR);
4321 case STOP_SENDING_FRAME:
4322 set_detailed_error(
4323 "Attempt to append STOP_SENDING frame and not in version 99.");
4324 return RaiseError(QUIC_INTERNAL_ERROR);
4325 case MESSAGE_FRAME:
4326 return true;
4327
4328 default:
4329 type_byte = static_cast<uint8_t>(frame.type);
4330 break;
4331 }
4332
4333 return writer->WriteUInt8(type_byte);
4334}
4335
4336bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4337 bool last_frame_in_packet,
4338 QuicDataWriter* writer) {
4339 uint8_t type_byte = 0;
4340 switch (frame.type) {
4341 case PADDING_FRAME:
4342 type_byte = IETF_PADDING;
4343 break;
4344 case RST_STREAM_FRAME:
4345 type_byte = IETF_RST_STREAM;
4346 break;
4347 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004348 switch (frame.connection_close_frame->close_type) {
4349 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4350 type_byte = IETF_APPLICATION_CLOSE;
4351 break;
4352 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4353 type_byte = IETF_CONNECTION_CLOSE;
4354 break;
4355 default:
4356 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4357 return RaiseError(QUIC_INTERNAL_ERROR);
4358 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004359 break;
4360 case GOAWAY_FRAME:
4361 set_detailed_error(
4362 "Attempt to create non-version-99 GOAWAY frame in version 99.");
4363 return RaiseError(QUIC_INTERNAL_ERROR);
4364 case WINDOW_UPDATE_FRAME:
4365 // Depending on whether there is a stream ID or not, will be either a
4366 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4367 if (frame.window_update_frame->stream_id ==
4368 QuicUtils::GetInvalidStreamId(transport_version())) {
4369 type_byte = IETF_MAX_DATA;
4370 } else {
4371 type_byte = IETF_MAX_STREAM_DATA;
4372 }
4373 break;
4374 case BLOCKED_FRAME:
4375 if (frame.blocked_frame->stream_id ==
4376 QuicUtils::GetInvalidStreamId(transport_version())) {
4377 type_byte = IETF_BLOCKED;
4378 } else {
4379 type_byte = IETF_STREAM_BLOCKED;
4380 }
4381 break;
4382 case STOP_WAITING_FRAME:
4383 set_detailed_error(
4384 "Attempt to append type byte of STOP WAITING frame in version 99.");
4385 return RaiseError(QUIC_INTERNAL_ERROR);
4386 case PING_FRAME:
4387 type_byte = IETF_PING;
4388 break;
4389 case STREAM_FRAME:
4390 type_byte =
4391 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4392 break;
4393 case ACK_FRAME:
4394 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4395 // in the buffer.
4396 return true;
4397 case MTU_DISCOVERY_FRAME:
4398 // The path MTU discovery frame is encoded as a PING frame on the wire.
4399 type_byte = IETF_PING;
4400 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004401 case NEW_CONNECTION_ID_FRAME:
4402 type_byte = IETF_NEW_CONNECTION_ID;
4403 break;
4404 case RETIRE_CONNECTION_ID_FRAME:
4405 type_byte = IETF_RETIRE_CONNECTION_ID;
4406 break;
4407 case NEW_TOKEN_FRAME:
4408 type_byte = IETF_NEW_TOKEN;
4409 break;
4410 case MAX_STREAM_ID_FRAME:
4411 if (QuicUtils::IsBidirectionalStreamId(
4412 frame.max_stream_id_frame.max_stream_id)) {
4413 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
4414 } else {
4415 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
4416 }
4417 break;
4418 case STREAM_ID_BLOCKED_FRAME:
4419 if (QuicUtils::IsBidirectionalStreamId(
4420 frame.max_stream_id_frame.max_stream_id)) {
4421 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
4422 } else {
4423 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
4424 }
4425 break;
4426 case PATH_RESPONSE_FRAME:
4427 type_byte = IETF_PATH_RESPONSE;
4428 break;
4429 case PATH_CHALLENGE_FRAME:
4430 type_byte = IETF_PATH_CHALLENGE;
4431 break;
4432 case STOP_SENDING_FRAME:
4433 type_byte = IETF_STOP_SENDING;
4434 break;
4435 case MESSAGE_FRAME:
4436 return true;
4437 case CRYPTO_FRAME:
4438 type_byte = IETF_CRYPTO;
4439 break;
4440 default:
4441 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4442 << frame.type;
4443 return false;
4444 }
4445 return writer->WriteUInt8(type_byte);
4446}
4447
4448// static
4449bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4450 QuicPacketNumber packet_number,
4451 QuicDataWriter* writer) {
4452 DCHECK(packet_number.IsInitialized());
4453 if (!IsValidPacketNumberLength(packet_number_length)) {
4454 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4455 return false;
4456 }
4457 return writer->WriteBytesToUInt64(packet_number_length,
4458 packet_number.ToUint64());
4459}
4460
4461// static
4462bool QuicFramer::AppendStreamId(size_t stream_id_length,
4463 QuicStreamId stream_id,
4464 QuicDataWriter* writer) {
4465 if (stream_id_length == 0 || stream_id_length > 4) {
4466 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4467 return false;
4468 }
4469 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4470}
4471
4472// static
4473bool QuicFramer::AppendStreamOffset(size_t offset_length,
4474 QuicStreamOffset offset,
4475 QuicDataWriter* writer) {
4476 if (offset_length == 1 || offset_length > 8) {
4477 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4478 return false;
4479 }
4480
4481 return writer->WriteBytesToUInt64(offset_length, offset);
4482}
4483
4484// static
4485bool QuicFramer::AppendAckBlock(uint8_t gap,
4486 QuicPacketNumberLength length_length,
4487 uint64_t length,
4488 QuicDataWriter* writer) {
4489 if (length == 0) {
4490 if (!IsValidPacketNumberLength(length_length)) {
4491 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4492 return false;
4493 }
4494 return writer->WriteUInt8(gap) &&
4495 writer->WriteBytesToUInt64(length_length, length);
4496 }
4497 return writer->WriteUInt8(gap) &&
4498 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4499}
4500
4501bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4502 bool no_stream_frame_length,
4503 QuicDataWriter* writer) {
4504 if (version_.transport_version == QUIC_VERSION_99) {
4505 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4506 }
4507 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4508 writer)) {
4509 QUIC_BUG << "Writing stream id size failed.";
4510 return false;
4511 }
4512 if (!AppendStreamOffset(
4513 GetStreamOffsetSize(version_.transport_version, frame.offset),
4514 frame.offset, writer)) {
4515 QUIC_BUG << "Writing offset size failed.";
4516 return false;
4517 }
4518 if (!no_stream_frame_length) {
4519 if ((frame.data_length > std::numeric_limits<uint16_t>::max()) ||
4520 !writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
4521 QUIC_BUG << "Writing stream frame length failed";
4522 return false;
4523 }
4524 }
4525
4526 if (data_producer_ != nullptr) {
4527 DCHECK_EQ(nullptr, frame.data_buffer);
4528 if (frame.data_length == 0) {
4529 return true;
4530 }
4531 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
4532 frame.data_length,
4533 writer) != WRITE_SUCCESS) {
4534 QUIC_BUG << "Writing frame data failed.";
4535 return false;
4536 }
4537 return true;
4538 }
4539
4540 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
4541 QUIC_BUG << "Writing frame data failed.";
4542 return false;
4543 }
4544 return true;
4545}
4546
4547// static
4548bool QuicFramer::AppendIetfConnectionId(
4549 bool version_flag,
4550 QuicConnectionId destination_connection_id,
4551 QuicConnectionIdLength destination_connection_id_length,
4552 QuicConnectionId source_connection_id,
4553 QuicConnectionIdLength source_connection_id_length,
4554 QuicDataWriter* writer) {
4555 if (version_flag) {
4556 // Append connection ID length byte.
4557 uint8_t dcil = GetConnectionIdLengthValue(destination_connection_id_length);
4558 uint8_t scil = GetConnectionIdLengthValue(source_connection_id_length);
4559 uint8_t connection_id_length = dcil << 4 | scil;
4560 if (!writer->WriteBytes(&connection_id_length, 1)) {
4561 return false;
4562 }
4563 }
4564 if (destination_connection_id_length == PACKET_8BYTE_CONNECTION_ID &&
4565 !writer->WriteConnectionId(destination_connection_id)) {
4566 return false;
4567 }
4568 if (source_connection_id_length == PACKET_8BYTE_CONNECTION_ID &&
4569 !writer->WriteConnectionId(source_connection_id)) {
4570 return false;
4571 }
4572 return true;
4573}
4574
4575bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
4576 QuicDataWriter* writer) {
4577 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
4578 set_detailed_error("Writing token length failed.");
4579 return false;
4580 }
4581 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
4582 set_detailed_error("Writing token buffer failed.");
4583 return false;
4584 }
4585 return true;
4586}
4587
4588bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
4589 QuicNewTokenFrame* frame) {
4590 uint64_t length;
4591 if (!reader->ReadVarInt62(&length)) {
4592 set_detailed_error("Unable to read new token length.");
4593 return false;
4594 }
4595 if (length > kMaxNewTokenTokenLength) {
4596 set_detailed_error("Token length larger than maximum.");
4597 return false;
4598 }
4599
4600 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
4601 QuicStringPiece data;
4602 if (!reader->ReadStringPiece(&data, length)) {
4603 set_detailed_error("Unable to read new token data.");
4604 return false;
4605 }
vasilvvc48c8712019-03-11 13:38:16 -07004606 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004607 return true;
4608}
4609
4610// Add a new ietf-format stream frame.
4611// Bits controlling whether there is a frame-length and frame-offset
4612// are in the QuicStreamFrame.
4613bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
4614 bool last_frame_in_packet,
4615 QuicDataWriter* writer) {
4616 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
4617 set_detailed_error("Writing stream id failed.");
4618 return false;
4619 }
4620
4621 if (frame.offset != 0) {
4622 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
4623 set_detailed_error("Writing data offset failed.");
4624 return false;
4625 }
4626 }
4627
4628 if (!last_frame_in_packet) {
4629 if (!writer->WriteVarInt62(frame.data_length)) {
4630 set_detailed_error("Writing data length failed.");
4631 return false;
4632 }
4633 }
4634
4635 if (frame.data_length == 0) {
4636 return true;
4637 }
4638 if (data_producer_ == nullptr) {
4639 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
4640 set_detailed_error("Writing frame data failed.");
4641 return false;
4642 }
4643 } else {
4644 DCHECK_EQ(nullptr, frame.data_buffer);
4645
4646 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
4647 frame.data_length,
4648 writer) != WRITE_SUCCESS) {
4649 set_detailed_error("Writing frame data failed.");
4650 return false;
4651 }
4652 }
4653 return true;
4654}
4655
4656bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
4657 QuicDataWriter* writer) {
4658 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
4659 set_detailed_error("Writing data offset failed.");
4660 return false;
4661 }
4662 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
4663 set_detailed_error("Writing data length failed.");
4664 return false;
4665 }
4666 if (data_producer_ == nullptr) {
4667 if (frame.data_buffer == nullptr ||
4668 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
4669 set_detailed_error("Writing frame data failed.");
4670 return false;
4671 }
4672 } else {
4673 DCHECK_EQ(nullptr, frame.data_buffer);
4674 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
4675 frame.data_length, writer)) {
4676 return false;
4677 }
4678 }
4679 return true;
4680}
4681
4682void QuicFramer::set_version(const ParsedQuicVersion version) {
4683 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
4684 version_ = version;
4685}
4686
4687bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
4688 QuicDataWriter* writer) {
4689 if (transport_version() == QUIC_VERSION_99) {
4690 return AppendIetfAckFrameAndTypeByte(frame, writer);
4691 }
4692
4693 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
4694 QuicPacketNumber largest_acked = LargestAcked(frame);
4695 QuicPacketNumberLength largest_acked_length =
4696 GetMinPacketNumberLength(version_.transport_version, largest_acked);
4697 QuicPacketNumberLength ack_block_length =
4698 GetMinPacketNumberLength(version_.transport_version,
4699 QuicPacketNumber(new_ack_info.max_block_length));
4700 // Calculate available bytes for timestamps and ack blocks.
4701 int32_t available_timestamp_and_ack_block_bytes =
4702 writer->capacity() - writer->length() - ack_block_length -
4703 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
4704 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
4705 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
4706
4707 // Write out the type byte by setting the low order bits and doing shifts
4708 // to make room for the next bit flags to be set.
4709 // Whether there are multiple ack blocks.
4710 uint8_t type_byte = 0;
4711 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
4712 kQuicHasMultipleAckBlocksOffset);
4713
4714 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
4715 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
4716
4717 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
4718 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
4719
4720 type_byte |= kQuicFrameTypeAckMask;
4721
4722 if (!writer->WriteUInt8(type_byte)) {
4723 return false;
4724 }
4725
4726 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
4727 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4728
4729 // Number of ack blocks.
4730 size_t num_ack_blocks =
4731 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
4732 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
4733 num_ack_blocks = std::numeric_limits<uint8_t>::max();
4734 }
4735
4736 // Largest acked.
4737 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
4738 return false;
4739 }
4740
4741 // Largest acked delta time.
4742 uint64_t ack_delay_time_us = kUFloat16MaxValue;
4743 if (!frame.ack_delay_time.IsInfinite()) {
4744 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
4745 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
4746 }
4747 if (!writer->WriteUFloat16(ack_delay_time_us)) {
4748 return false;
4749 }
4750
4751 if (num_ack_blocks > 0) {
4752 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
4753 return false;
4754 }
4755 }
4756
4757 // First ack block length.
4758 if (!AppendPacketNumber(ack_block_length,
4759 QuicPacketNumber(new_ack_info.first_block_length),
4760 writer)) {
4761 return false;
4762 }
4763
4764 // Ack blocks.
4765 if (num_ack_blocks > 0) {
4766 size_t num_ack_blocks_written = 0;
4767 // Append, in descending order from the largest ACKed packet, a series of
4768 // ACK blocks that represents the successfully acknoweldged packets. Each
4769 // appended gap/block length represents a descending delta from the previous
4770 // block. i.e.:
4771 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
4772 // For gaps larger than can be represented by a single encoded gap, a 0
4773 // length gap of the maximum is used, i.e.:
4774 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
4775 auto itr = frame.packets.rbegin();
4776 QuicPacketNumber previous_start = itr->min();
4777 ++itr;
4778
4779 for (;
4780 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
4781 previous_start = itr->min(), ++itr) {
4782 const auto& interval = *itr;
4783 const uint64_t total_gap = previous_start - interval.max();
4784 const size_t num_encoded_gaps =
4785 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
4786 std::numeric_limits<uint8_t>::max();
4787 DCHECK_LE(0u, num_encoded_gaps);
4788
4789 // Append empty ACK blocks because the gap is longer than a single gap.
4790 for (size_t i = 1;
4791 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
4792 ++i) {
4793 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
4794 ack_block_length, 0, writer)) {
4795 return false;
4796 }
4797 ++num_ack_blocks_written;
4798 }
4799 if (num_ack_blocks_written >= num_ack_blocks) {
4800 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
4801 QUIC_BUG << "Wrote " << num_ack_blocks_written
4802 << ", expected to write " << num_ack_blocks;
4803 }
4804 break;
4805 }
4806
4807 const uint8_t last_gap =
4808 total_gap -
4809 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
4810 // Append the final ACK block with a non-empty size.
4811 if (!AppendAckBlock(last_gap, ack_block_length,
4812 PacketNumberIntervalLength(interval), writer)) {
4813 return false;
4814 }
4815 ++num_ack_blocks_written;
4816 }
4817 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
4818 }
4819 // Timestamps.
4820 // If we don't process timestamps or if we don't have enough available space
4821 // to append all the timestamps, don't append any of them.
4822 if (process_timestamps_ && writer->capacity() - writer->length() >=
4823 GetAckFrameTimeStampSize(frame)) {
4824 if (!AppendTimestampsToAckFrame(frame, writer)) {
4825 return false;
4826 }
4827 } else {
4828 uint8_t num_received_packets = 0;
4829 if (!writer->WriteBytes(&num_received_packets, 1)) {
4830 return false;
4831 }
4832 }
4833
4834 return true;
4835}
4836
4837bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
4838 QuicDataWriter* writer) {
4839 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
4840 frame.received_packet_times.size());
4841 // num_received_packets is only 1 byte.
4842 if (frame.received_packet_times.size() >
4843 std::numeric_limits<uint8_t>::max()) {
4844 return false;
4845 }
4846
4847 uint8_t num_received_packets = frame.received_packet_times.size();
4848 if (!writer->WriteBytes(&num_received_packets, 1)) {
4849 return false;
4850 }
4851 if (num_received_packets == 0) {
4852 return true;
4853 }
4854
4855 auto it = frame.received_packet_times.begin();
4856 QuicPacketNumber packet_number = it->first;
4857 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
4858
4859 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
4860 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
4861 return false;
4862 }
4863
4864 if (!writer->WriteUInt8(delta_from_largest_observed)) {
4865 return false;
4866 }
4867
4868 // Use the lowest 4 bytes of the time delta from the creation_time_.
4869 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
4870 uint32_t time_delta_us =
4871 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
4872 (time_epoch_delta_us - 1));
4873 if (!writer->WriteUInt32(time_delta_us)) {
4874 return false;
4875 }
4876
4877 QuicTime prev_time = it->second;
4878
4879 for (++it; it != frame.received_packet_times.end(); ++it) {
4880 packet_number = it->first;
4881 delta_from_largest_observed = LargestAcked(frame) - packet_number;
4882
4883 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
4884 return false;
4885 }
4886
4887 if (!writer->WriteUInt8(delta_from_largest_observed)) {
4888 return false;
4889 }
4890
4891 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
4892 prev_time = it->second;
4893 if (!writer->WriteUFloat16(frame_time_delta_us)) {
4894 return false;
4895 }
4896 }
4897 return true;
4898}
4899
4900bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
4901 const QuicStopWaitingFrame& frame,
4902 QuicDataWriter* writer) {
4903 DCHECK_GE(QUIC_VERSION_43, version_.transport_version);
4904 DCHECK(frame.least_unacked.IsInitialized() &&
4905 header.packet_number >= frame.least_unacked);
4906 const uint64_t least_unacked_delta =
4907 header.packet_number - frame.least_unacked;
4908 const uint64_t length_shift = header.packet_number_length * 8;
4909
4910 if (least_unacked_delta >> length_shift > 0) {
4911 QUIC_BUG << "packet_number_length " << header.packet_number_length
4912 << " is too small for least_unacked_delta: " << least_unacked_delta
4913 << " packet_number:" << header.packet_number
4914 << " least_unacked:" << frame.least_unacked
4915 << " version:" << version_.transport_version;
4916 return false;
4917 }
4918 if (least_unacked_delta == 0) {
4919 return writer->WriteBytesToUInt64(header.packet_number_length,
4920 least_unacked_delta);
4921 }
4922 if (!AppendPacketNumber(header.packet_number_length,
4923 QuicPacketNumber(least_unacked_delta), writer)) {
4924 QUIC_BUG << " seq failed: " << header.packet_number_length;
4925 return false;
4926 }
4927
4928 return true;
4929}
4930
4931int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
4932 QuicDataWriter* writer,
4933 size_t available_space) {
4934 // Number of blocks requested in the frame
4935 uint64_t ack_block_count = frame.packets.NumIntervals();
4936
4937 auto itr = frame.packets.rbegin();
4938
4939 int actual_block_count = 1;
4940 uint64_t block_length = itr->max() - itr->min();
4941 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
4942 if (encoded_size > available_space) {
4943 return 0;
4944 }
4945 available_space -= encoded_size;
4946 QuicPacketNumber previous_ack_end = itr->min();
4947 ack_block_count--;
4948
4949 while (ack_block_count) {
4950 // Each block is a gap followed by another ACK. Calculate each value,
4951 // determine the encoded lengths, and check against the available space.
4952 itr++;
4953 size_t gap = previous_ack_end - itr->max() - 1;
4954 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
4955
4956 // Add the ACK block.
4957 block_length = itr->max() - itr->min();
4958 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
4959
4960 if (encoded_size > available_space) {
4961 // No room for this block, so what we've
4962 // done up to now is all that can be done.
4963 return actual_block_count;
4964 }
4965 available_space -= encoded_size;
4966 actual_block_count++;
4967 previous_ack_end = itr->min();
4968 ack_block_count--;
4969 }
4970 // Ran through the whole thing! We can do all blocks.
4971 return actual_block_count;
4972}
4973
4974bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
4975 QuicDataWriter* writer) {
4976 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
4977 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
4978 uint8_t type = IETF_ACK;
4979 if (frame.ecn_counters_populated &&
4980 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4981 type = IETF_ACK_ECN;
4982 }
4983
4984 if (!writer->WriteUInt8(type)) {
4985 set_detailed_error("No room for frame-type");
4986 return false;
4987 }
4988
4989 QuicPacketNumber largest_acked = LargestAcked(frame);
4990 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
4991 set_detailed_error("No room for largest-acked in ack frame");
4992 return false;
4993 }
4994
4995 uint64_t ack_delay_time_us = kVarInt62MaxValue;
4996 if (!frame.ack_delay_time.IsInfinite()) {
4997 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
4998 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
4999 // TODO(fkastenholz): Use the shift from TLS transport parameters.
5000 ack_delay_time_us = ack_delay_time_us >> kIetfAckTimestampShift;
5001 }
5002
5003 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5004 set_detailed_error("No room for ack-delay in ack frame");
5005 return false;
5006 }
5007 if (type == IETF_ACK_ECN) {
5008 // Encode the ACK ECN fields
5009 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5010 set_detailed_error("No room for ect_0_count in ack frame");
5011 return false;
5012 }
5013 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5014 set_detailed_error("No room for ect_1_count in ack frame");
5015 return false;
5016 }
5017 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5018 set_detailed_error("No room for ecn_ce_count in ack frame");
5019 return false;
5020 }
5021 }
5022
5023 uint64_t ack_block_count = frame.packets.NumIntervals();
5024 if (ack_block_count == 0) {
5025 // If the QuicAckFrame has no Intervals, then it is interpreted
5026 // as an ack of a single packet at QuicAckFrame.largest_acked.
5027 // The resulting ack will consist of only the frame's
5028 // largest_ack & first_ack_block fields. The first ack block will be 0
5029 // (indicating a single packet) and the ack block_count will be 0.
5030 if (!writer->WriteVarInt62(0)) {
5031 set_detailed_error("No room for ack block count in ack frame");
5032 return false;
5033 }
5034 // size of the first block is 1 packet
5035 if (!writer->WriteVarInt62(0)) {
5036 set_detailed_error("No room for first ack block in ack frame");
5037 return false;
5038 }
5039 return true;
5040 }
5041 // Case 2 or 3
5042 auto itr = frame.packets.rbegin();
5043
5044 QuicPacketNumber ack_block_largest(largest_acked);
5045 QuicPacketNumber ack_block_smallest;
5046 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5047 // If largest_acked + 1 is equal to the Max() of the first Interval
5048 // in the QuicAckFrame then the first Interval is the first ack block of the
5049 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5050 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5051 // the remaining Intervals are encoded in additional ack blocks in the
5052 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5053 // Intervals - 1.
5054 ack_block_smallest = itr->min();
5055 itr++;
5056 ack_block_count--;
5057 } else {
5058 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5059 // the first Interval then it is interpreted as acking a single
5060 // packet at QuicAckFrame.largest_acked, with additional
5061 // Intervals indicating additional ack blocks. The encoding is
5062 // a) The packet's largest_acked is the QuicAckFrame's largest
5063 // acked,
5064 // b) the first ack block size is 0,
5065 // c) The packet's ack_block_count is the number of QuicAckFrame
5066 // Intervals, and
5067 // d) The QuicAckFrame Intervals are encoded in additional ack
5068 // blocks in the packet.
5069 ack_block_smallest = largest_acked;
5070 }
5071
5072 if (!writer->WriteVarInt62(ack_block_count)) {
5073 set_detailed_error("No room for ack block count in ack frame");
5074 return false;
5075 }
5076
5077 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5078 if (!writer->WriteVarInt62(first_ack_block)) {
5079 set_detailed_error("No room for first ack block in ack frame");
5080 return false;
5081 }
5082
5083 // For the remaining QuicAckFrame Intervals, if any
5084 while (ack_block_count != 0) {
5085 uint64_t gap_size = ack_block_smallest - itr->max();
5086 if (!writer->WriteVarInt62(gap_size - 1)) {
5087 set_detailed_error("No room for gap block in ack frame");
5088 return false;
5089 }
5090
5091 uint64_t block_size = itr->max() - itr->min();
5092 if (!writer->WriteVarInt62(block_size - 1)) {
5093 set_detailed_error("No room for nth ack block in ack frame");
5094 return false;
5095 }
5096
5097 ack_block_smallest = itr->min();
5098 itr++;
5099 ack_block_count--;
5100 }
5101 return true;
5102}
5103
5104bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5105 QuicDataWriter* writer) {
5106 if (version_.transport_version == QUIC_VERSION_99) {
5107 return AppendIetfResetStreamFrame(frame, writer);
5108 }
5109 if (!writer->WriteUInt32(frame.stream_id)) {
5110 return false;
5111 }
5112
5113 if (!writer->WriteUInt64(frame.byte_offset)) {
5114 return false;
5115 }
5116
5117 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5118 if (!writer->WriteUInt32(error_code)) {
5119 return false;
5120 }
5121
5122 return true;
5123}
5124
5125bool QuicFramer::AppendConnectionCloseFrame(
5126 const QuicConnectionCloseFrame& frame,
5127 QuicDataWriter* writer) {
5128 if (version_.transport_version == QUIC_VERSION_99) {
5129 return AppendIetfConnectionCloseFrame(frame, writer);
5130 }
fkastenholze9d71a82019-04-09 05:12:13 -07005131 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005132 if (!writer->WriteUInt32(error_code)) {
5133 return false;
5134 }
5135 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5136 return false;
5137 }
5138 return true;
5139}
5140
5141bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5142 QuicDataWriter* writer) {
5143 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5144 if (!writer->WriteUInt32(error_code)) {
5145 return false;
5146 }
5147 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5148 if (!writer->WriteUInt32(stream_id)) {
5149 return false;
5150 }
5151 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5152 return false;
5153 }
5154 return true;
5155}
5156
5157bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5158 QuicDataWriter* writer) {
5159 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5160 if (!writer->WriteUInt32(stream_id)) {
5161 return false;
5162 }
5163 if (!writer->WriteUInt64(frame.byte_offset)) {
5164 return false;
5165 }
5166 return true;
5167}
5168
5169bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5170 QuicDataWriter* writer) {
5171 if (version_.transport_version == QUIC_VERSION_99) {
5172 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5173 return AppendIetfBlockedFrame(frame, writer);
5174 }
5175 return AppendStreamBlockedFrame(frame, writer);
5176 }
5177 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5178 if (!writer->WriteUInt32(stream_id)) {
5179 return false;
5180 }
5181 return true;
5182}
5183
5184bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5185 QuicDataWriter* writer) {
5186 if (frame.num_padding_bytes == 0) {
5187 return false;
5188 }
5189 if (frame.num_padding_bytes < 0) {
5190 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5191 writer->WritePadding();
5192 return true;
5193 }
5194 // Please note, num_padding_bytes includes type byte which has been written.
5195 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5196}
5197
5198bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5199 bool last_frame_in_packet,
5200 QuicDataWriter* writer) {
5201 uint8_t type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5202 : IETF_EXTENSION_MESSAGE;
5203 if (!writer->WriteUInt8(type_byte)) {
5204 return false;
5205 }
5206 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5207 return false;
5208 }
5209 for (const auto& slice : frame.message_data) {
5210 if (!writer->WriteBytes(slice.data(), slice.length())) {
5211 return false;
5212 }
5213 }
5214 return true;
5215}
5216
5217bool QuicFramer::RaiseError(QuicErrorCode error) {
5218 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5219 << " detail: " << detailed_error_;
5220 set_error(error);
5221 visitor_->OnError(this);
5222 return false;
5223}
5224
5225bool QuicFramer::IsVersionNegotiation(
5226 const QuicPacketHeader& header,
5227 bool packet_has_ietf_packet_header) const {
5228 if (perspective_ == Perspective::IS_SERVER) {
5229 return false;
5230 }
5231 if (!packet_has_ietf_packet_header) {
5232 return header.version_flag;
5233 }
5234 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5235 return false;
5236 }
5237 return header.long_packet_type == VERSION_NEGOTIATION;
5238}
5239
QUICHE teama6ef0a62019-03-07 20:34:33 -05005240bool QuicFramer::AppendIetfConnectionCloseFrame(
5241 const QuicConnectionCloseFrame& frame,
5242 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005243 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5244 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5245 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5246 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5247 return false;
5248 }
5249
fkastenholze9d71a82019-04-09 05:12:13 -07005250 if (!writer->WriteUInt16(frame.application_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005251 set_detailed_error("Can not write connection close frame error code");
5252 return false;
5253 }
fkastenholze9d71a82019-04-09 05:12:13 -07005254
fkastenholz72f509b2019-04-10 09:17:49 -07005255 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5256 // Write the frame-type of the frame causing the error only
5257 // if it's a CONNECTION_CLOSE/Transport.
5258 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5259 set_detailed_error("Writing frame type failed.");
5260 return false;
5261 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005262 }
5263
fkastenholz72f509b2019-04-10 09:17:49 -07005264 // TODO(fkastenholz): For full IETF CONNECTION CLOSE support,
5265 // if this is a Transport CONNECTION_CLOSE and the extended
5266 // error is not QUIC_IETF_GQUIC_ERROR_MISSING then append the extended
5267 // "QuicErrorCode: #" string to the phrase.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005268 if (!writer->WriteStringPieceVarInt62(
5269 TruncateErrorString(frame.error_details))) {
5270 set_detailed_error("Can not write connection close phrase");
5271 return false;
5272 }
5273 return true;
5274}
5275
QUICHE teama6ef0a62019-03-07 20:34:33 -05005276bool QuicFramer::ProcessIetfConnectionCloseFrame(
5277 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005278 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005279 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005280 frame->close_type = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005281 uint16_t code;
5282 if (!reader->ReadUInt16(&code)) {
5283 set_detailed_error("Unable to read connection close error code.");
5284 return false;
5285 }
fkastenholze9d71a82019-04-09 05:12:13 -07005286 frame->transport_error_code = static_cast<QuicIetfTransportErrorCodes>(code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005287
fkastenholz72f509b2019-04-10 09:17:49 -07005288 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5289 // The frame-type of the frame causing the error is present only
5290 // if it's a CONNECTION_CLOSE/Transport.
5291 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5292 set_detailed_error("Unable to read connection close frame type.");
5293 return false;
5294 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005295 }
5296
5297 uint64_t phrase_length;
5298 if (!reader->ReadVarInt62(&phrase_length)) {
5299 set_detailed_error("Unable to read connection close error details.");
5300 return false;
5301 }
5302 QuicStringPiece phrase;
5303 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5304 set_detailed_error("Unable to read connection close error details.");
5305 return false;
5306 }
fkastenholz72f509b2019-04-10 09:17:49 -07005307 // TODO(fkastenholz): when full support is done, add code here
5308 // to extract the extended error code from the reason phrase
5309 // and set it into frame->extracted_error_code.
vasilvvc48c8712019-03-11 13:38:16 -07005310 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005311
5312 return true;
5313}
5314
5315// IETF Quic Path Challenge/Response frames.
5316bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5317 QuicPathChallengeFrame* frame) {
5318 if (!reader->ReadBytes(frame->data_buffer.data(),
5319 frame->data_buffer.size())) {
5320 set_detailed_error("Can not read path challenge data.");
5321 return false;
5322 }
5323 return true;
5324}
5325
5326bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5327 QuicPathResponseFrame* frame) {
5328 if (!reader->ReadBytes(frame->data_buffer.data(),
5329 frame->data_buffer.size())) {
5330 set_detailed_error("Can not read path response data.");
5331 return false;
5332 }
5333 return true;
5334}
5335
5336bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5337 QuicDataWriter* writer) {
5338 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5339 set_detailed_error("Writing Path Challenge data failed.");
5340 return false;
5341 }
5342 return true;
5343}
5344
5345bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5346 QuicDataWriter* writer) {
5347 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5348 set_detailed_error("Writing Path Response data failed.");
5349 return false;
5350 }
5351 return true;
5352}
5353
5354// Add a new ietf-format stream reset frame.
5355// General format is
5356// stream id
5357// application error code
5358// final offset
5359bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5360 QuicDataWriter* writer) {
5361 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5362 set_detailed_error("Writing reset-stream stream id failed.");
5363 return false;
5364 }
5365 if (!writer->WriteUInt16(frame.ietf_error_code)) {
5366 set_detailed_error("Writing reset-stream error code failed.");
5367 return false;
5368 }
5369 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5370 set_detailed_error("Writing reset-stream final-offset failed.");
5371 return false;
5372 }
5373 return true;
5374}
5375
5376bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5377 QuicRstStreamFrame* frame) {
5378 // Get Stream ID from frame. ReadVarIntStreamID returns false
5379 // if either A) there is a read error or B) the resulting value of
5380 // the Stream ID is larger than the maximum allowed value.
5381 if (!reader->ReadVarIntStreamId(&frame->stream_id)) {
5382 set_detailed_error("Unable to read rst stream stream id.");
5383 return false;
5384 }
5385
5386 if (!reader->ReadUInt16(&frame->ietf_error_code)) {
5387 set_detailed_error("Unable to read rst stream error code.");
5388 return false;
5389 }
5390
5391 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5392 set_detailed_error("Unable to read rst stream sent byte offset.");
5393 return false;
5394 }
5395 return true;
5396}
5397
5398bool QuicFramer::ProcessStopSendingFrame(
5399 QuicDataReader* reader,
5400 QuicStopSendingFrame* stop_sending_frame) {
5401 if (!reader->ReadVarIntStreamId(&stop_sending_frame->stream_id)) {
5402 set_detailed_error("Unable to read stop sending stream id.");
5403 return false;
5404 }
5405
5406 if (!reader->ReadUInt16(&stop_sending_frame->application_error_code)) {
5407 set_detailed_error("Unable to read stop sending application error code.");
5408 return false;
5409 }
5410 return true;
5411}
5412
5413bool QuicFramer::AppendStopSendingFrame(
5414 const QuicStopSendingFrame& stop_sending_frame,
5415 QuicDataWriter* writer) {
5416 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5417 set_detailed_error("Can not write stop sending stream id");
5418 return false;
5419 }
5420 if (!writer->WriteUInt16(stop_sending_frame.application_error_code)) {
5421 set_detailed_error("Can not write application error code");
5422 return false;
5423 }
5424 return true;
5425}
5426
5427// Append/process IETF-Format MAX_DATA Frame
5428bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5429 QuicDataWriter* writer) {
5430 if (!writer->WriteVarInt62(frame.byte_offset)) {
5431 set_detailed_error("Can not write MAX_DATA byte-offset");
5432 return false;
5433 }
5434 return true;
5435}
5436
5437bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5438 QuicWindowUpdateFrame* frame) {
5439 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5440 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5441 set_detailed_error("Can not read MAX_DATA byte-offset");
5442 return false;
5443 }
5444 return true;
5445}
5446
5447// Append/process IETF-Format MAX_STREAM_DATA Frame
5448bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5449 QuicDataWriter* writer) {
5450 if (!writer->WriteVarInt62(frame.stream_id)) {
5451 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5452 return false;
5453 }
5454 if (!writer->WriteVarInt62(frame.byte_offset)) {
5455 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5456 return false;
5457 }
5458 return true;
5459}
5460
5461bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5462 QuicWindowUpdateFrame* frame) {
5463 if (!reader->ReadVarIntStreamId(&frame->stream_id)) {
5464 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5465 return false;
5466 }
5467 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5468 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5469 return false;
5470 }
5471 return true;
5472}
5473
5474bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamIdFrame& frame,
5475 QuicDataWriter* writer) {
5476 // Convert from the stream id on which the connection is blocked to a count
5477 QuicStreamId stream_count =
5478 StreamIdToCount(version_.transport_version, frame.max_stream_id);
5479
5480 if (!writer->WriteVarInt62(stream_count)) {
5481 set_detailed_error("Can not write MAX_STREAMS stream count");
5482 return false;
5483 }
5484 return true;
5485}
5486
5487bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
5488 QuicMaxStreamIdFrame* frame,
5489 uint64_t frame_type) {
5490 QuicStreamId received_stream_count;
5491 if (!reader->ReadVarIntStreamId(&received_stream_count)) {
5492 set_detailed_error("Can not read MAX_STREAMS stream count.");
5493 return false;
5494 }
5495 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
5496 // frame is implemented and passed up to the stream ID manager.
5497 if (received_stream_count == 0) {
5498 set_detailed_error("MAX_STREAMS stream count of 0 not supported.");
5499 return false;
5500 }
5501 // Note that this code assumes that the only possible error that
5502 // StreamCountToId can detect is that the stream count is too big or is 0.
5503 // Too big is prevented by passing in the minimum of the received count
5504 // and the maximum supported count, ensuring that the stream ID is
5505 // pegged at the maximum allowed ID.
5506 // count==0 is handled above, so that detailed_error_ may be set
5507 // properly.
5508 return StreamCountToId(
5509 std::min(
5510 received_stream_count,
5511 GetMaxStreamCount((frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL),
5512 perspective_)),
5513 /*unidirectional=*/(frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL),
5514 perspective_, version_.transport_version, &frame->max_stream_id);
5515}
5516
5517bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
5518 QuicDataWriter* writer) {
5519 if (!writer->WriteVarInt62(frame.offset)) {
5520 set_detailed_error("Can not write blocked offset.");
5521 return false;
5522 }
5523 return true;
5524}
5525
5526bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
5527 QuicBlockedFrame* frame) {
5528 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
5529 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5530 if (!reader->ReadVarInt62(&frame->offset)) {
5531 set_detailed_error("Can not read blocked offset.");
5532 return false;
5533 }
5534 return true;
5535}
5536
5537bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
5538 QuicDataWriter* writer) {
5539 if (!writer->WriteVarInt62(frame.stream_id)) {
5540 set_detailed_error("Can not write stream blocked stream id.");
5541 return false;
5542 }
5543 if (!writer->WriteVarInt62(frame.offset)) {
5544 set_detailed_error("Can not write stream blocked offset.");
5545 return false;
5546 }
5547 return true;
5548}
5549
5550bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
5551 QuicBlockedFrame* frame) {
5552 if (!reader->ReadVarIntStreamId(&frame->stream_id)) {
5553 set_detailed_error("Can not read stream blocked stream id.");
5554 return false;
5555 }
5556 if (!reader->ReadVarInt62(&frame->offset)) {
5557 set_detailed_error("Can not read stream blocked offset.");
5558 return false;
5559 }
5560 return true;
5561}
5562
5563bool QuicFramer::AppendStreamsBlockedFrame(
5564 const QuicStreamIdBlockedFrame& frame,
5565 QuicDataWriter* writer) {
5566 // Convert from the stream id on which the connection is blocked to a count
5567 QuicStreamId stream_count =
5568 StreamIdToCount(version_.transport_version, frame.stream_id);
5569
5570 if (!writer->WriteVarInt62(stream_count)) {
5571 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
5572 return false;
5573 }
5574 return true;
5575}
5576
5577bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
5578 QuicStreamIdBlockedFrame* frame,
5579 uint64_t frame_type) {
5580 QuicStreamId received_stream_count;
5581 if (!reader->ReadVarIntStreamId(&received_stream_count)) {
5582 set_detailed_error("Can not read STREAMS_BLOCKED stream id.");
5583 return false;
5584 }
5585 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
5586 // frame is implemented and passed up to the stream ID manager.
5587 if (received_stream_count == 0) {
5588 set_detailed_error("STREAMS_BLOCKED stream count 0 not supported.");
5589 return false;
5590 }
5591 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
5592 // frame is implemented and passed up to the stream ID manager.
5593 if (received_stream_count >
5594 GetMaxStreamCount((frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL),
5595 ((perspective_ == Perspective::IS_CLIENT)
5596 ? Perspective::IS_SERVER
5597 : Perspective::IS_CLIENT))) {
5598 // If stream count is such that the resulting stream ID would exceed our
5599 // implementation limit, generate an error.
5600 set_detailed_error(
5601 "STREAMS_BLOCKED stream count exceeds implementation limit.");
5602 return false;
5603 }
5604 // Convert the stream count to an ID that can be used.
5605 // The STREAMS_BLOCKED frame is a request for more streams
5606 // that the peer will initiate. If this node is a client, it
5607 // means that the peer is a server, and wants server-initiated
5608 // stream IDs.
5609 return StreamCountToId(
5610 received_stream_count,
5611 /*unidirectional=*/(frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
5612 (perspective_ == Perspective::IS_CLIENT) ? Perspective::IS_SERVER
5613 : Perspective::IS_CLIENT,
5614 version_.transport_version, &frame->stream_id);
5615}
5616
5617bool QuicFramer::AppendNewConnectionIdFrame(
5618 const QuicNewConnectionIdFrame& frame,
5619 QuicDataWriter* writer) {
5620 if (!writer->WriteVarInt62(frame.sequence_number)) {
5621 set_detailed_error("Can not write New Connection ID sequence number");
5622 return false;
5623 }
5624 if (!writer->WriteUInt8(frame.connection_id.length())) {
5625 set_detailed_error(
5626 "Can not write New Connection ID frame connection ID Length");
5627 return false;
5628 }
5629 if (!writer->WriteConnectionId(frame.connection_id)) {
5630 set_detailed_error("Can not write New Connection ID frame connection ID");
5631 return false;
5632 }
5633
5634 if (!writer->WriteBytes(
5635 static_cast<const void*>(&frame.stateless_reset_token),
5636 sizeof(frame.stateless_reset_token))) {
5637 set_detailed_error("Can not write New Connection ID Reset Token");
5638 return false;
5639 }
5640 return true;
5641}
5642
5643bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
5644 QuicNewConnectionIdFrame* frame) {
5645 if (!reader->ReadVarInt62(&frame->sequence_number)) {
5646 set_detailed_error(
5647 "Unable to read new connection ID frame sequence number.");
5648 return false;
5649 }
5650
5651 uint8_t connection_id_length;
5652 if (!reader->ReadUInt8(&connection_id_length)) {
5653 set_detailed_error(
5654 "Unable to read new connection ID frame connection id length.");
5655 return false;
5656 }
5657
QUICHE team0131a5b2019-03-20 15:23:27 -07005658 if (connection_id_length > kQuicMaxConnectionIdLength) {
5659 set_detailed_error("New connection ID length too high.");
5660 return false;
5661 }
5662
QUICHE team8e2e4532019-03-14 14:37:56 -07005663 if (connection_id_length != kQuicDefaultConnectionIdLength &&
5664 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
5665 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07005666 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05005667 return false;
5668 }
5669
5670 if (!reader->ReadConnectionId(&frame->connection_id, connection_id_length)) {
5671 set_detailed_error("Unable to read new connection ID frame connection id.");
5672 return false;
5673 }
5674
5675 if (!reader->ReadBytes(&frame->stateless_reset_token,
5676 sizeof(frame->stateless_reset_token))) {
5677 set_detailed_error("Can not read new connection ID frame reset token.");
5678 return false;
5679 }
5680 return true;
5681}
5682
5683bool QuicFramer::AppendRetireConnectionIdFrame(
5684 const QuicRetireConnectionIdFrame& frame,
5685 QuicDataWriter* writer) {
5686 if (!writer->WriteVarInt62(frame.sequence_number)) {
5687 set_detailed_error("Can not write Retire Connection ID sequence number");
5688 return false;
5689 }
5690 return true;
5691}
5692
5693bool QuicFramer::ProcessRetireConnectionIdFrame(
5694 QuicDataReader* reader,
5695 QuicRetireConnectionIdFrame* frame) {
5696 if (!reader->ReadVarInt62(&frame->sequence_number)) {
5697 set_detailed_error(
5698 "Unable to read retire connection ID frame sequence number.");
5699 return false;
5700 }
5701 return true;
5702}
5703
5704uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
5705 bool last_frame_in_packet) const {
5706 if (version_.transport_version == QUIC_VERSION_99) {
5707 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
5708 }
5709 uint8_t type_byte = 0;
5710 // Fin bit.
5711 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
5712
5713 // Data Length bit.
5714 type_byte <<= kQuicStreamDataLengthShift;
5715 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
5716
5717 // Offset 3 bits.
5718 type_byte <<= kQuicStreamShift;
5719 const size_t offset_len =
5720 GetStreamOffsetSize(version_.transport_version, frame.offset);
5721 if (offset_len > 0) {
5722 type_byte |= offset_len - 1;
5723 }
5724
5725 // stream id 2 bits.
5726 type_byte <<= kQuicStreamIdShift;
5727 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
5728 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
5729
5730 return type_byte;
5731}
5732
5733uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
5734 const QuicStreamFrame& frame,
5735 bool last_frame_in_packet) const {
5736 DCHECK_EQ(QUIC_VERSION_99, version_.transport_version);
5737 uint8_t type_byte = IETF_STREAM;
5738 if (!last_frame_in_packet) {
5739 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
5740 }
5741 if (frame.offset != 0) {
5742 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
5743 }
5744 if (frame.fin) {
5745 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
5746 }
5747 return type_byte;
5748}
5749
5750void QuicFramer::InferPacketHeaderTypeFromVersion() {
5751 // This function should only be called when server connection negotiates the
5752 // version.
5753 DCHECK(perspective_ == Perspective::IS_SERVER &&
5754 !infer_packet_header_type_from_version_);
5755 infer_packet_header_type_from_version_ = true;
5756}
5757
QUICHE team10b22a12019-03-21 15:31:42 -07005758void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
5759 if (supports_multiple_packet_number_spaces_) {
5760 QUIC_BUG << "Multiple packet number spaces has already been enabled";
5761 return;
5762 }
5763 if (largest_packet_number_.IsInitialized()) {
5764 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
5765 "packet has been received.";
5766 return;
5767 }
5768
5769 supports_multiple_packet_number_spaces_ = true;
5770}
5771
QUICHE teama6ef0a62019-03-07 20:34:33 -05005772#undef ENDPOINT // undef for jumbo builds
5773} // namespace quic