1 // 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/quic/quic_framer.h"
6
7 #include "base/containers/hash_tables.h"
8 #include "base/stl_util.h"
9 #include "net/quic/crypto/crypto_framer.h"
10 #include "net/quic/crypto/crypto_handshake_message.h"
11 #include "net/quic/crypto/crypto_protocol.h"
12 #include "net/quic/crypto/quic_decrypter.h"
13 #include "net/quic/crypto/quic_encrypter.h"
14 #include "net/quic/quic_data_reader.h"
15 #include "net/quic/quic_data_writer.h"
16 #include "net/quic/quic_flags.h"
17 #include "net/quic/quic_socket_address_coder.h"
18
19 using base::StringPiece;
20 using std::make_pair;
21 using std::map;
22 using std::max;
23 using std::min;
24 using std::numeric_limits;
25 using std::string;
26
27 namespace net {
28
29 namespace {
30
31 // Mask to select the lowest 48 bits of a sequence number.
32 const QuicPacketSequenceNumber k6ByteSequenceNumberMask =
33 GG_UINT64_C(0x0000FFFFFFFFFFFF);
34 const QuicPacketSequenceNumber k4ByteSequenceNumberMask =
35 GG_UINT64_C(0x00000000FFFFFFFF);
36 const QuicPacketSequenceNumber k2ByteSequenceNumberMask =
37 GG_UINT64_C(0x000000000000FFFF);
38 const QuicPacketSequenceNumber k1ByteSequenceNumberMask =
39 GG_UINT64_C(0x00000000000000FF);
40
41 const QuicConnectionId k1ByteConnectionIdMask = GG_UINT64_C(0x00000000000000FF);
42 const QuicConnectionId k4ByteConnectionIdMask = GG_UINT64_C(0x00000000FFFFFFFF);
43
44 // Number of bits the sequence number length bits are shifted from the right
45 // edge of the public header.
46 const uint8 kPublicHeaderSequenceNumberShift = 4;
47
48 // New Frame Types, QUIC v. >= 10:
49 // There are two interpretations for the Frame Type byte in the QUIC protocol,
50 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
51 //
52 // Regular Frame Types use the Frame Type byte simply. Currently defined
53 // Regular Frame Types are:
54 // Padding : 0b 00000000 (0x00)
55 // ResetStream : 0b 00000001 (0x01)
56 // ConnectionClose : 0b 00000010 (0x02)
57 // GoAway : 0b 00000011 (0x03)
58 // WindowUpdate : 0b 00000100 (0x04)
59 // Blocked : 0b 00000101 (0x05)
60 //
61 // Special Frame Types encode both a Frame Type and corresponding flags
62 // all in the Frame Type byte. Currently defined Special Frame Types are:
63 // Stream : 0b 1xxxxxxx
64 // Ack : 0b 01xxxxxx
65 // CongestionFeedback : 0b 001xxxxx
66 //
67 // Semantics of the flag bits above (the x bits) depends on the frame type.
68
69 // Masks to determine if the frame type is a special use
70 // and for specific special frame types.
71 const uint8 kQuicFrameTypeSpecialMask = 0xE0; // 0b 11100000
72 const uint8 kQuicFrameTypeStreamMask = 0x80;
73 const uint8 kQuicFrameTypeAckMask = 0x40;
74 const uint8 kQuicFrameTypeCongestionFeedbackMask = 0x20;
75
76 // Stream frame relative shifts and masks for interpreting the stream flags.
77 // StreamID may be 1, 2, 3, or 4 bytes.
78 const uint8 kQuicStreamIdShift = 2;
79 const uint8 kQuicStreamIDLengthMask = 0x03;
80
81 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
82 const uint8 kQuicStreamOffsetShift = 3;
83 const uint8 kQuicStreamOffsetMask = 0x07;
84
85 // Data length may be 0 or 2 bytes.
86 const uint8 kQuicStreamDataLengthShift = 1;
87 const uint8 kQuicStreamDataLengthMask = 0x01;
88
89 // Fin bit may be set or not.
90 const uint8 kQuicStreamFinShift = 1;
91 const uint8 kQuicStreamFinMask = 0x01;
92
93 // Sequence number size shift used in AckFrames.
94 const uint8 kQuicSequenceNumberLengthShift = 2;
95
96 // Acks may be truncated.
97 const uint8 kQuicAckTruncatedShift = 1;
98 const uint8 kQuicAckTruncatedMask = 0x01;
99
100 // Acks may not have any nacks.
101 const uint8 kQuicHasNacksMask = 0x01;
102
103 // Returns the absolute value of the difference between |a| and |b|.
Delta(QuicPacketSequenceNumber a,QuicPacketSequenceNumber b)104 QuicPacketSequenceNumber Delta(QuicPacketSequenceNumber a,
105 QuicPacketSequenceNumber b) {
106 // Since these are unsigned numbers, we can't just return abs(a - b)
107 if (a < b) {
108 return b - a;
109 }
110 return a - b;
111 }
112
ClosestTo(QuicPacketSequenceNumber target,QuicPacketSequenceNumber a,QuicPacketSequenceNumber b)113 QuicPacketSequenceNumber ClosestTo(QuicPacketSequenceNumber target,
114 QuicPacketSequenceNumber a,
115 QuicPacketSequenceNumber b) {
116 return (Delta(target, a) < Delta(target, b)) ? a : b;
117 }
118
ReadSequenceNumberLength(uint8 flags)119 QuicSequenceNumberLength ReadSequenceNumberLength(uint8 flags) {
120 switch (flags & PACKET_FLAGS_6BYTE_SEQUENCE) {
121 case PACKET_FLAGS_6BYTE_SEQUENCE:
122 return PACKET_6BYTE_SEQUENCE_NUMBER;
123 case PACKET_FLAGS_4BYTE_SEQUENCE:
124 return PACKET_4BYTE_SEQUENCE_NUMBER;
125 case PACKET_FLAGS_2BYTE_SEQUENCE:
126 return PACKET_2BYTE_SEQUENCE_NUMBER;
127 case PACKET_FLAGS_1BYTE_SEQUENCE:
128 return PACKET_1BYTE_SEQUENCE_NUMBER;
129 default:
130 LOG(DFATAL) << "Unreachable case statement.";
131 return PACKET_6BYTE_SEQUENCE_NUMBER;
132 }
133 }
134
CanTruncate(QuicVersion version,const QuicFrame & frame,size_t free_bytes)135 bool CanTruncate(
136 QuicVersion version, const QuicFrame& frame, size_t free_bytes) {
137 if ((frame.type == ACK_FRAME || frame.type == CONNECTION_CLOSE_FRAME) &&
138 free_bytes >=
139 QuicFramer::GetMinAckFrameSize(version,
140 PACKET_6BYTE_SEQUENCE_NUMBER,
141 PACKET_6BYTE_SEQUENCE_NUMBER)) {
142 return true;
143 }
144 return false;
145 }
146
147 } // namespace
148
OnWindowUpdateFrame(const QuicWindowUpdateFrame & frame)149 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
150 const QuicWindowUpdateFrame& frame) {
151 return true;
152 }
153
OnBlockedFrame(const QuicBlockedFrame & frame)154 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame& frame) {
155 return true;
156 }
157
QuicFramer(const QuicVersionVector & supported_versions,QuicTime creation_time,bool is_server)158 QuicFramer::QuicFramer(const QuicVersionVector& supported_versions,
159 QuicTime creation_time,
160 bool is_server)
161 : visitor_(NULL),
162 fec_builder_(NULL),
163 entropy_calculator_(NULL),
164 error_(QUIC_NO_ERROR),
165 last_sequence_number_(0),
166 last_serialized_connection_id_(0),
167 supported_versions_(supported_versions),
168 decrypter_level_(ENCRYPTION_NONE),
169 alternative_decrypter_level_(ENCRYPTION_NONE),
170 alternative_decrypter_latch_(false),
171 is_server_(is_server),
172 validate_flags_(true),
173 creation_time_(creation_time) {
174 DCHECK(!supported_versions.empty());
175 quic_version_ = supported_versions_[0];
176 decrypter_.reset(QuicDecrypter::Create(kNULL));
177 encrypter_[ENCRYPTION_NONE].reset(
178 QuicEncrypter::Create(kNULL));
179 }
180
~QuicFramer()181 QuicFramer::~QuicFramer() {}
182
183 // static
GetMinStreamFrameSize(QuicVersion version,QuicStreamId stream_id,QuicStreamOffset offset,bool last_frame_in_packet,InFecGroup is_in_fec_group)184 size_t QuicFramer::GetMinStreamFrameSize(QuicVersion version,
185 QuicStreamId stream_id,
186 QuicStreamOffset offset,
187 bool last_frame_in_packet,
188 InFecGroup is_in_fec_group) {
189 bool no_stream_frame_length = last_frame_in_packet &&
190 is_in_fec_group == NOT_IN_FEC_GROUP;
191 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
192 GetStreamOffsetSize(offset) +
193 (no_stream_frame_length ? 0 : kQuicStreamPayloadLengthSize);
194 }
195
196 // static
GetMinAckFrameSize(QuicVersion version,QuicSequenceNumberLength sequence_number_length,QuicSequenceNumberLength largest_observed_length)197 size_t QuicFramer::GetMinAckFrameSize(
198 QuicVersion version,
199 QuicSequenceNumberLength sequence_number_length,
200 QuicSequenceNumberLength largest_observed_length) {
201 size_t len = kQuicFrameTypeSize + kQuicEntropyHashSize +
202 largest_observed_length + kQuicDeltaTimeLargestObservedSize;
203 if (version <= QUIC_VERSION_15) {
204 len += sequence_number_length + kQuicEntropyHashSize;
205 }
206 return len;
207 }
208
209 // static
GetStopWaitingFrameSize(QuicSequenceNumberLength sequence_number_length)210 size_t QuicFramer::GetStopWaitingFrameSize(
211 QuicSequenceNumberLength sequence_number_length) {
212 return kQuicFrameTypeSize + kQuicEntropyHashSize +
213 sequence_number_length;
214 }
215
216 // static
GetMinRstStreamFrameSize(QuicVersion quic_version)217 size_t QuicFramer::GetMinRstStreamFrameSize(QuicVersion quic_version) {
218 return kQuicFrameTypeSize + kQuicMaxStreamIdSize +
219 kQuicMaxStreamOffsetSize + kQuicErrorCodeSize +
220 kQuicErrorDetailsLengthSize;
221 }
222
223 // static
GetMinConnectionCloseFrameSize()224 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
225 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize;
226 }
227
228 // static
GetMinGoAwayFrameSize()229 size_t QuicFramer::GetMinGoAwayFrameSize() {
230 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
231 kQuicMaxStreamIdSize;
232 }
233
234 // static
GetWindowUpdateFrameSize()235 size_t QuicFramer::GetWindowUpdateFrameSize() {
236 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
237 }
238
239 // static
GetBlockedFrameSize()240 size_t QuicFramer::GetBlockedFrameSize() {
241 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
242 }
243
244 // static
GetStreamIdSize(QuicStreamId stream_id)245 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
246 // Sizes are 1 through 4 bytes.
247 for (int i = 1; i <= 4; ++i) {
248 stream_id >>= 8;
249 if (stream_id == 0) {
250 return i;
251 }
252 }
253 LOG(DFATAL) << "Failed to determine StreamIDSize.";
254 return 4;
255 }
256
257 // static
GetStreamOffsetSize(QuicStreamOffset offset)258 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
259 // 0 is a special case.
260 if (offset == 0) {
261 return 0;
262 }
263 // 2 through 8 are the remaining sizes.
264 offset >>= 8;
265 for (int i = 2; i <= 8; ++i) {
266 offset >>= 8;
267 if (offset == 0) {
268 return i;
269 }
270 }
271 LOG(DFATAL) << "Failed to determine StreamOffsetSize.";
272 return 8;
273 }
274
275 // static
GetVersionNegotiationPacketSize(size_t number_versions)276 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions) {
277 return kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID +
278 number_versions * kQuicVersionSize;
279 }
280
IsSupportedVersion(const QuicVersion version) const281 bool QuicFramer::IsSupportedVersion(const QuicVersion version) const {
282 for (size_t i = 0; i < supported_versions_.size(); ++i) {
283 if (version == supported_versions_[i]) {
284 return true;
285 }
286 }
287 return false;
288 }
289
GetSerializedFrameLength(const QuicFrame & frame,size_t free_bytes,bool first_frame,bool last_frame,InFecGroup is_in_fec_group,QuicSequenceNumberLength sequence_number_length)290 size_t QuicFramer::GetSerializedFrameLength(
291 const QuicFrame& frame,
292 size_t free_bytes,
293 bool first_frame,
294 bool last_frame,
295 InFecGroup is_in_fec_group,
296 QuicSequenceNumberLength sequence_number_length) {
297 if (frame.type == PADDING_FRAME) {
298 // PADDING implies end of packet.
299 return free_bytes;
300 }
301 size_t frame_len =
302 ComputeFrameLength(frame, last_frame, is_in_fec_group,
303 sequence_number_length);
304 if (frame_len <= free_bytes) {
305 // Frame fits within packet. Note that acks may be truncated.
306 return frame_len;
307 }
308 // Only truncate the first frame in a packet, so if subsequent ones go
309 // over, stop including more frames.
310 if (!first_frame) {
311 return 0;
312 }
313 if (CanTruncate(quic_version_, frame, free_bytes)) {
314 // Truncate the frame so the packet will not exceed kMaxPacketSize.
315 // Note that we may not use every byte of the writer in this case.
316 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes;
317 return free_bytes;
318 }
319 if (!FLAGS_quic_allow_oversized_packets_for_test) {
320 return 0;
321 }
322 LOG(DFATAL) << "Packet size too small to fit frame.";
323 return frame_len;
324 }
325
AckFrameInfo()326 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
327
~AckFrameInfo()328 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
329
GetPacketEntropyHash(const QuicPacketHeader & header) const330 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash(
331 const QuicPacketHeader& header) const {
332 return header.entropy_flag << (header.packet_sequence_number % 8);
333 }
334
BuildDataPacket(const QuicPacketHeader & header,const QuicFrames & frames,size_t packet_size)335 SerializedPacket QuicFramer::BuildDataPacket(
336 const QuicPacketHeader& header,
337 const QuicFrames& frames,
338 size_t packet_size) {
339 QuicDataWriter writer(packet_size);
340 const SerializedPacket kNoPacket(
341 0, PACKET_1BYTE_SEQUENCE_NUMBER, NULL, 0, NULL);
342 if (!AppendPacketHeader(header, &writer)) {
343 LOG(DFATAL) << "AppendPacketHeader failed";
344 return kNoPacket;
345 }
346
347 for (size_t i = 0; i < frames.size(); ++i) {
348 const QuicFrame& frame = frames[i];
349
350 // Determine if we should write stream frame length in header.
351 const bool no_stream_frame_length =
352 (header.is_in_fec_group == NOT_IN_FEC_GROUP) &&
353 (i == frames.size() - 1);
354 if (!AppendTypeByte(frame, no_stream_frame_length, &writer)) {
355 LOG(DFATAL) << "AppendTypeByte failed";
356 return kNoPacket;
357 }
358
359 switch (frame.type) {
360 case PADDING_FRAME:
361 writer.WritePadding();
362 break;
363 case STREAM_FRAME:
364 if (!AppendStreamFrame(
365 *frame.stream_frame, no_stream_frame_length, &writer)) {
366 LOG(DFATAL) << "AppendStreamFrame failed";
367 return kNoPacket;
368 }
369 break;
370 case ACK_FRAME:
371 if (!AppendAckFrameAndTypeByte(
372 header, *frame.ack_frame, &writer)) {
373 LOG(DFATAL) << "AppendAckFrameAndTypeByte failed";
374 return kNoPacket;
375 }
376 break;
377 case CONGESTION_FEEDBACK_FRAME:
378 if (!AppendCongestionFeedbackFrame(
379 *frame.congestion_feedback_frame, &writer)) {
380 LOG(DFATAL) << "AppendCongestionFeedbackFrame failed";
381 return kNoPacket;
382 }
383 break;
384 case STOP_WAITING_FRAME:
385 if (quic_version_ <= QUIC_VERSION_15) {
386 LOG(DFATAL) << "Attempt to add a StopWaitingFrame in "
387 << QuicVersionToString(quic_version_);
388 return kNoPacket;
389 }
390 if (!AppendStopWaitingFrame(
391 header, *frame.stop_waiting_frame, &writer)) {
392 LOG(DFATAL) << "AppendStopWaitingFrame failed";
393 return kNoPacket;
394 }
395 break;
396 case PING_FRAME:
397 if (quic_version_ <= QUIC_VERSION_17) {
398 LOG(DFATAL) << "Attempt to add a PingFrame in "
399 << QuicVersionToString(quic_version_);
400 return kNoPacket;
401 }
402 // Ping has no payload.
403 break;
404 case RST_STREAM_FRAME:
405 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
406 LOG(DFATAL) << "AppendRstStreamFrame failed";
407 return kNoPacket;
408 }
409 break;
410 case CONNECTION_CLOSE_FRAME:
411 if (!AppendConnectionCloseFrame(
412 *frame.connection_close_frame, &writer)) {
413 LOG(DFATAL) << "AppendConnectionCloseFrame failed";
414 return kNoPacket;
415 }
416 break;
417 case GOAWAY_FRAME:
418 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
419 LOG(DFATAL) << "AppendGoAwayFrame failed";
420 return kNoPacket;
421 }
422 break;
423 case WINDOW_UPDATE_FRAME:
424 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
425 LOG(DFATAL) << "AppendWindowUpdateFrame failed";
426 return kNoPacket;
427 }
428 break;
429 case BLOCKED_FRAME:
430 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
431 LOG(DFATAL) << "AppendBlockedFrame failed";
432 return kNoPacket;
433 }
434 break;
435 default:
436 RaiseError(QUIC_INVALID_FRAME_DATA);
437 LOG(DFATAL) << "QUIC_INVALID_FRAME_DATA";
438 return kNoPacket;
439 }
440 }
441
442 // Save the length before writing, because take clears it.
443 const size_t len = writer.length();
444 // Less than or equal because truncated acks end up with max_plaintex_size
445 // length, even though they're typically slightly shorter.
446 DCHECK_LE(len, packet_size);
447 QuicPacket* packet = QuicPacket::NewDataPacket(
448 writer.take(), len, true, header.public_header.connection_id_length,
449 header.public_header.version_flag,
450 header.public_header.sequence_number_length);
451
452 if (fec_builder_) {
453 fec_builder_->OnBuiltFecProtectedPayload(header,
454 packet->FecProtectedData());
455 }
456
457 return SerializedPacket(header.packet_sequence_number,
458 header.public_header.sequence_number_length, packet,
459 GetPacketEntropyHash(header), NULL);
460 }
461
BuildFecPacket(const QuicPacketHeader & header,const QuicFecData & fec)462 SerializedPacket QuicFramer::BuildFecPacket(const QuicPacketHeader& header,
463 const QuicFecData& fec) {
464 DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group);
465 DCHECK_NE(0u, header.fec_group);
466 size_t len = GetPacketHeaderSize(header);
467 len += fec.redundancy.length();
468
469 QuicDataWriter writer(len);
470 const SerializedPacket kNoPacket(
471 0, PACKET_1BYTE_SEQUENCE_NUMBER, NULL, 0, NULL);
472 if (!AppendPacketHeader(header, &writer)) {
473 LOG(DFATAL) << "AppendPacketHeader failed";
474 return kNoPacket;
475 }
476
477 if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) {
478 LOG(DFATAL) << "Failed to add FEC";
479 return kNoPacket;
480 }
481
482 return SerializedPacket(
483 header.packet_sequence_number,
484 header.public_header.sequence_number_length,
485 QuicPacket::NewFecPacket(writer.take(), len, true,
486 header.public_header.connection_id_length,
487 header.public_header.version_flag,
488 header.public_header.sequence_number_length),
489 GetPacketEntropyHash(header), NULL);
490 }
491
492 // static
BuildPublicResetPacket(const QuicPublicResetPacket & packet)493 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket(
494 const QuicPublicResetPacket& packet) {
495 DCHECK(packet.public_header.reset_flag);
496
497 CryptoHandshakeMessage reset;
498 reset.set_tag(kPRST);
499 reset.SetValue(kRNON, packet.nonce_proof);
500 reset.SetValue(kRSEQ, packet.rejected_sequence_number);
501 if (!packet.client_address.address().empty()) {
502 // packet.client_address is non-empty.
503 QuicSocketAddressCoder address_coder(packet.client_address);
504 string serialized_address = address_coder.Encode();
505 if (serialized_address.empty()) {
506 return NULL;
507 }
508 reset.SetStringPiece(kCADR, serialized_address);
509 }
510 const QuicData& reset_serialized = reset.GetSerialized();
511
512 size_t len =
513 kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + reset_serialized.length();
514 QuicDataWriter writer(len);
515
516 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST |
517 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
518 if (!writer.WriteUInt8(flags)) {
519 return NULL;
520 }
521
522 if (!writer.WriteUInt64(packet.public_header.connection_id)) {
523 return NULL;
524 }
525
526 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
527 return NULL;
528 }
529
530 return new QuicEncryptedPacket(writer.take(), len, true);
531 }
532
BuildVersionNegotiationPacket(const QuicPacketPublicHeader & header,const QuicVersionVector & supported_versions)533 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket(
534 const QuicPacketPublicHeader& header,
535 const QuicVersionVector& supported_versions) {
536 DCHECK(header.version_flag);
537 size_t len = GetVersionNegotiationPacketSize(supported_versions.size());
538 QuicDataWriter writer(len);
539
540 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION |
541 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
542 if (!writer.WriteUInt8(flags)) {
543 return NULL;
544 }
545
546 if (!writer.WriteUInt64(header.connection_id)) {
547 return NULL;
548 }
549
550 for (size_t i = 0; i < supported_versions.size(); ++i) {
551 if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) {
552 return NULL;
553 }
554 }
555
556 return new QuicEncryptedPacket(writer.take(), len, true);
557 }
558
ProcessPacket(const QuicEncryptedPacket & packet)559 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
560 DCHECK(!reader_.get());
561 reader_.reset(new QuicDataReader(packet.data(), packet.length()));
562
563 visitor_->OnPacket();
564
565 // First parse the public header.
566 QuicPacketPublicHeader public_header;
567 if (!ProcessPublicHeader(&public_header)) {
568 DLOG(WARNING) << "Unable to process public header.";
569 DCHECK_NE("", detailed_error_);
570 return RaiseError(QUIC_INVALID_PACKET_HEADER);
571 }
572
573 if (!visitor_->OnUnauthenticatedPublicHeader(public_header)) {
574 // The visitor suppresses further processing of the packet.
575 reader_.reset(NULL);
576 return true;
577 }
578
579 if (is_server_ && public_header.version_flag &&
580 public_header.versions[0] != quic_version_) {
581 if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) {
582 reader_.reset(NULL);
583 return true;
584 }
585 }
586
587 bool rv;
588 if (!is_server_ && public_header.version_flag) {
589 rv = ProcessVersionNegotiationPacket(&public_header);
590 } else if (public_header.reset_flag) {
591 rv = ProcessPublicResetPacket(public_header);
592 } else {
593 rv = ProcessDataPacket(public_header, packet);
594 }
595
596 reader_.reset(NULL);
597 return rv;
598 }
599
ProcessVersionNegotiationPacket(QuicPacketPublicHeader * public_header)600 bool QuicFramer::ProcessVersionNegotiationPacket(
601 QuicPacketPublicHeader* public_header) {
602 DCHECK(!is_server_);
603 // Try reading at least once to raise error if the packet is invalid.
604 do {
605 QuicTag version;
606 if (!reader_->ReadBytes(&version, kQuicVersionSize)) {
607 set_detailed_error("Unable to read supported version in negotiation.");
608 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
609 }
610 public_header->versions.push_back(QuicTagToQuicVersion(version));
611 } while (!reader_->IsDoneReading());
612
613 visitor_->OnVersionNegotiationPacket(*public_header);
614 return true;
615 }
616
ProcessDataPacket(const QuicPacketPublicHeader & public_header,const QuicEncryptedPacket & packet)617 bool QuicFramer::ProcessDataPacket(
618 const QuicPacketPublicHeader& public_header,
619 const QuicEncryptedPacket& packet) {
620 QuicPacketHeader header(public_header);
621 if (!ProcessPacketHeader(&header, packet)) {
622 DLOG(WARNING) << "Unable to process data packet header.";
623 return false;
624 }
625
626 if (!visitor_->OnPacketHeader(header)) {
627 // The visitor suppresses further processing of the packet.
628 return true;
629 }
630
631 if (packet.length() > kMaxPacketSize) {
632 DLOG(WARNING) << "Packet too large: " << packet.length();
633 return RaiseError(QUIC_PACKET_TOO_LARGE);
634 }
635
636 // Handle the payload.
637 if (!header.fec_flag) {
638 if (header.is_in_fec_group == IN_FEC_GROUP) {
639 StringPiece payload = reader_->PeekRemainingPayload();
640 visitor_->OnFecProtectedPayload(payload);
641 }
642 if (!ProcessFrameData(header)) {
643 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
644 DLOG(WARNING) << "Unable to process frame data.";
645 return false;
646 }
647 } else {
648 QuicFecData fec_data;
649 fec_data.fec_group = header.fec_group;
650 fec_data.redundancy = reader_->ReadRemainingPayload();
651 visitor_->OnFecData(fec_data);
652 }
653
654 visitor_->OnPacketComplete();
655 return true;
656 }
657
ProcessPublicResetPacket(const QuicPacketPublicHeader & public_header)658 bool QuicFramer::ProcessPublicResetPacket(
659 const QuicPacketPublicHeader& public_header) {
660 QuicPublicResetPacket packet(public_header);
661
662 scoped_ptr<CryptoHandshakeMessage> reset(
663 CryptoFramer::ParseMessage(reader_->ReadRemainingPayload()));
664 if (!reset.get()) {
665 set_detailed_error("Unable to read reset message.");
666 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
667 }
668 if (reset->tag() != kPRST) {
669 set_detailed_error("Incorrect message tag.");
670 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
671 }
672
673 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
674 set_detailed_error("Unable to read nonce proof.");
675 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
676 }
677 // TODO(satyamshekhar): validate nonce to protect against DoS.
678
679 if (reset->GetUint64(kRSEQ, &packet.rejected_sequence_number) !=
680 QUIC_NO_ERROR) {
681 set_detailed_error("Unable to read rejected sequence number.");
682 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
683 }
684
685 StringPiece address;
686 if (reset->GetStringPiece(kCADR, &address)) {
687 QuicSocketAddressCoder address_coder;
688 if (address_coder.Decode(address.data(), address.length())) {
689 packet.client_address = IPEndPoint(address_coder.ip(),
690 address_coder.port());
691 }
692 }
693
694 visitor_->OnPublicResetPacket(packet);
695 return true;
696 }
697
ProcessRevivedPacket(QuicPacketHeader * header,StringPiece payload)698 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header,
699 StringPiece payload) {
700 DCHECK(!reader_.get());
701
702 visitor_->OnRevivedPacket();
703
704 header->entropy_hash = GetPacketEntropyHash(*header);
705
706 if (!visitor_->OnPacketHeader(*header)) {
707 return true;
708 }
709
710 if (payload.length() > kMaxPacketSize) {
711 set_detailed_error("Revived packet too large.");
712 return RaiseError(QUIC_PACKET_TOO_LARGE);
713 }
714
715 reader_.reset(new QuicDataReader(payload.data(), payload.length()));
716 if (!ProcessFrameData(*header)) {
717 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
718 DLOG(WARNING) << "Unable to process frame data.";
719 return false;
720 }
721
722 visitor_->OnPacketComplete();
723 reader_.reset(NULL);
724 return true;
725 }
726
AppendPacketHeader(const QuicPacketHeader & header,QuicDataWriter * writer)727 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
728 QuicDataWriter* writer) {
729 DVLOG(1) << "Appending header: " << header;
730 DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP);
731 uint8 public_flags = 0;
732 if (header.public_header.reset_flag) {
733 public_flags |= PACKET_PUBLIC_FLAGS_RST;
734 }
735 if (header.public_header.version_flag) {
736 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
737 }
738
739 public_flags |=
740 GetSequenceNumberFlags(header.public_header.sequence_number_length)
741 << kPublicHeaderSequenceNumberShift;
742
743 switch (header.public_header.connection_id_length) {
744 case PACKET_0BYTE_CONNECTION_ID:
745 if (!writer->WriteUInt8(
746 public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
747 return false;
748 }
749 break;
750 case PACKET_1BYTE_CONNECTION_ID:
751 if (!writer->WriteUInt8(
752 public_flags | PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID)) {
753 return false;
754 }
755 if (!writer->WriteUInt8(
756 header.public_header.connection_id & k1ByteConnectionIdMask)) {
757 return false;
758 }
759 break;
760 case PACKET_4BYTE_CONNECTION_ID:
761 if (!writer->WriteUInt8(
762 public_flags | PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID)) {
763 return false;
764 }
765 if (!writer->WriteUInt32(
766 header.public_header.connection_id & k4ByteConnectionIdMask)) {
767 return false;
768 }
769 break;
770 case PACKET_8BYTE_CONNECTION_ID:
771 if (!writer->WriteUInt8(
772 public_flags | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID)) {
773 return false;
774 }
775 if (!writer->WriteUInt64(header.public_header.connection_id)) {
776 return false;
777 }
778 break;
779 }
780 last_serialized_connection_id_ = header.public_header.connection_id;
781
782 if (header.public_header.version_flag) {
783 DCHECK(!is_server_);
784 writer->WriteUInt32(QuicVersionToQuicTag(quic_version_));
785 }
786
787 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
788 header.packet_sequence_number, writer)) {
789 return false;
790 }
791
792 uint8 private_flags = 0;
793 if (header.entropy_flag) {
794 private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY;
795 }
796 if (header.is_in_fec_group == IN_FEC_GROUP) {
797 private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP;
798 }
799 if (header.fec_flag) {
800 private_flags |= PACKET_PRIVATE_FLAGS_FEC;
801 }
802 if (!writer->WriteUInt8(private_flags)) {
803 return false;
804 }
805
806 // The FEC group number is the sequence number of the first fec
807 // protected packet, or 0 if this packet is not protected.
808 if (header.is_in_fec_group == IN_FEC_GROUP) {
809 DCHECK_GE(header.packet_sequence_number, header.fec_group);
810 DCHECK_GT(255u, header.packet_sequence_number - header.fec_group);
811 // Offset from the current packet sequence number to the first fec
812 // protected packet.
813 uint8 first_fec_protected_packet_offset =
814 header.packet_sequence_number - header.fec_group;
815 if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) {
816 return false;
817 }
818 }
819
820 return true;
821 }
822
CalculatePacketSequenceNumberFromWire(QuicSequenceNumberLength sequence_number_length,QuicPacketSequenceNumber packet_sequence_number) const823 QuicPacketSequenceNumber QuicFramer::CalculatePacketSequenceNumberFromWire(
824 QuicSequenceNumberLength sequence_number_length,
825 QuicPacketSequenceNumber packet_sequence_number) const {
826 // The new sequence number might have wrapped to the next epoch, or
827 // it might have reverse wrapped to the previous epoch, or it might
828 // remain in the same epoch. Select the sequence number closest to the
829 // next expected sequence number, the previous sequence number plus 1.
830
831 // epoch_delta is the delta between epochs the sequence number was serialized
832 // with, so the correct value is likely the same epoch as the last sequence
833 // number or an adjacent epoch.
834 const QuicPacketSequenceNumber epoch_delta =
835 GG_UINT64_C(1) << (8 * sequence_number_length);
836 QuicPacketSequenceNumber next_sequence_number = last_sequence_number_ + 1;
837 QuicPacketSequenceNumber epoch = last_sequence_number_ & ~(epoch_delta - 1);
838 QuicPacketSequenceNumber prev_epoch = epoch - epoch_delta;
839 QuicPacketSequenceNumber next_epoch = epoch + epoch_delta;
840
841 return ClosestTo(next_sequence_number,
842 epoch + packet_sequence_number,
843 ClosestTo(next_sequence_number,
844 prev_epoch + packet_sequence_number,
845 next_epoch + packet_sequence_number));
846 }
847
ProcessPublicHeader(QuicPacketPublicHeader * public_header)848 bool QuicFramer::ProcessPublicHeader(
849 QuicPacketPublicHeader* public_header) {
850 uint8 public_flags;
851 if (!reader_->ReadBytes(&public_flags, 1)) {
852 set_detailed_error("Unable to read public flags.");
853 return false;
854 }
855
856 public_header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
857 public_header->version_flag =
858 (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
859
860 if (validate_flags_ &&
861 !public_header->version_flag && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
862 set_detailed_error("Illegal public flags value.");
863 return false;
864 }
865
866 if (public_header->reset_flag && public_header->version_flag) {
867 set_detailed_error("Got version flag in reset packet");
868 return false;
869 }
870
871 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
872 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
873 if (!reader_->ReadUInt64(&public_header->connection_id)) {
874 set_detailed_error("Unable to read ConnectionId.");
875 return false;
876 }
877 public_header->connection_id_length = PACKET_8BYTE_CONNECTION_ID;
878 break;
879 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID:
880 // If the connection_id is truncated, expect to read the last serialized
881 // connection_id.
882 if (!reader_->ReadBytes(&public_header->connection_id,
883 PACKET_4BYTE_CONNECTION_ID)) {
884 set_detailed_error("Unable to read ConnectionId.");
885 return false;
886 }
887 if ((public_header->connection_id & k4ByteConnectionIdMask) !=
888 (last_serialized_connection_id_ & k4ByteConnectionIdMask)) {
889 set_detailed_error("Truncated 4 byte ConnectionId does not match "
890 "previous connection_id.");
891 return false;
892 }
893 public_header->connection_id_length = PACKET_4BYTE_CONNECTION_ID;
894 public_header->connection_id = last_serialized_connection_id_;
895 break;
896 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID:
897 if (!reader_->ReadBytes(&public_header->connection_id,
898 PACKET_1BYTE_CONNECTION_ID)) {
899 set_detailed_error("Unable to read ConnectionId.");
900 return false;
901 }
902 if ((public_header->connection_id & k1ByteConnectionIdMask) !=
903 (last_serialized_connection_id_ & k1ByteConnectionIdMask)) {
904 set_detailed_error("Truncated 1 byte ConnectionId does not match "
905 "previous connection_id.");
906 return false;
907 }
908 public_header->connection_id_length = PACKET_1BYTE_CONNECTION_ID;
909 public_header->connection_id = last_serialized_connection_id_;
910 break;
911 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
912 public_header->connection_id_length = PACKET_0BYTE_CONNECTION_ID;
913 public_header->connection_id = last_serialized_connection_id_;
914 break;
915 }
916
917 public_header->sequence_number_length =
918 ReadSequenceNumberLength(
919 public_flags >> kPublicHeaderSequenceNumberShift);
920
921 // Read the version only if the packet is from the client.
922 // version flag from the server means version negotiation packet.
923 if (public_header->version_flag && is_server_) {
924 QuicTag version_tag;
925 if (!reader_->ReadUInt32(&version_tag)) {
926 set_detailed_error("Unable to read protocol version.");
927 return false;
928 }
929
930 // If the version from the new packet is the same as the version of this
931 // framer, then the public flags should be set to something we understand.
932 // If not, this raises an error.
933 QuicVersion version = QuicTagToQuicVersion(version_tag);
934 if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
935 set_detailed_error("Illegal public flags value.");
936 return false;
937 }
938 public_header->versions.push_back(version);
939 }
940 return true;
941 }
942
943 // static
GetMinSequenceNumberLength(QuicPacketSequenceNumber sequence_number)944 QuicSequenceNumberLength QuicFramer::GetMinSequenceNumberLength(
945 QuicPacketSequenceNumber sequence_number) {
946 if (sequence_number < 1 << (PACKET_1BYTE_SEQUENCE_NUMBER * 8)) {
947 return PACKET_1BYTE_SEQUENCE_NUMBER;
948 } else if (sequence_number < 1 << (PACKET_2BYTE_SEQUENCE_NUMBER * 8)) {
949 return PACKET_2BYTE_SEQUENCE_NUMBER;
950 } else if (sequence_number <
951 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER * 8)) {
952 return PACKET_4BYTE_SEQUENCE_NUMBER;
953 } else {
954 return PACKET_6BYTE_SEQUENCE_NUMBER;
955 }
956 }
957
958 // static
GetSequenceNumberFlags(QuicSequenceNumberLength sequence_number_length)959 uint8 QuicFramer::GetSequenceNumberFlags(
960 QuicSequenceNumberLength sequence_number_length) {
961 switch (sequence_number_length) {
962 case PACKET_1BYTE_SEQUENCE_NUMBER:
963 return PACKET_FLAGS_1BYTE_SEQUENCE;
964 case PACKET_2BYTE_SEQUENCE_NUMBER:
965 return PACKET_FLAGS_2BYTE_SEQUENCE;
966 case PACKET_4BYTE_SEQUENCE_NUMBER:
967 return PACKET_FLAGS_4BYTE_SEQUENCE;
968 case PACKET_6BYTE_SEQUENCE_NUMBER:
969 return PACKET_FLAGS_6BYTE_SEQUENCE;
970 default:
971 LOG(DFATAL) << "Unreachable case statement.";
972 return PACKET_FLAGS_6BYTE_SEQUENCE;
973 }
974 }
975
976 // static
GetAckFrameInfo(const QuicAckFrame & frame)977 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
978 const QuicAckFrame& frame) {
979 const ReceivedPacketInfo& received_info = frame.received_info;
980
981 AckFrameInfo ack_info;
982 if (!received_info.missing_packets.empty()) {
983 DCHECK_GE(received_info.largest_observed,
984 *received_info.missing_packets.rbegin());
985 size_t cur_range_length = 0;
986 SequenceNumberSet::const_iterator iter =
987 received_info.missing_packets.begin();
988 QuicPacketSequenceNumber last_missing = *iter;
989 ++iter;
990 for (; iter != received_info.missing_packets.end(); ++iter) {
991 if (cur_range_length != numeric_limits<uint8>::max() &&
992 *iter == (last_missing + 1)) {
993 ++cur_range_length;
994 } else {
995 ack_info.nack_ranges[last_missing - cur_range_length]
996 = cur_range_length;
997 cur_range_length = 0;
998 }
999 ack_info.max_delta = max(ack_info.max_delta, *iter - last_missing);
1000 last_missing = *iter;
1001 }
1002 // Include the last nack range.
1003 ack_info.nack_ranges[last_missing - cur_range_length] = cur_range_length;
1004 // Include the range to the largest observed.
1005 ack_info.max_delta = max(ack_info.max_delta,
1006 received_info.largest_observed - last_missing);
1007 }
1008 return ack_info;
1009 }
1010
ProcessPacketHeader(QuicPacketHeader * header,const QuicEncryptedPacket & packet)1011 bool QuicFramer::ProcessPacketHeader(
1012 QuicPacketHeader* header,
1013 const QuicEncryptedPacket& packet) {
1014 if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length,
1015 &header->packet_sequence_number)) {
1016 set_detailed_error("Unable to read sequence number.");
1017 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1018 }
1019
1020 if (header->packet_sequence_number == 0u) {
1021 set_detailed_error("Packet sequence numbers cannot be 0.");
1022 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1023 }
1024
1025 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1026 return false;
1027 }
1028
1029 if (!DecryptPayload(*header, packet)) {
1030 set_detailed_error("Unable to decrypt payload.");
1031 return RaiseError(QUIC_DECRYPTION_FAILURE);
1032 }
1033
1034 uint8 private_flags;
1035 if (!reader_->ReadBytes(&private_flags, 1)) {
1036 set_detailed_error("Unable to read private flags.");
1037 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1038 }
1039
1040 if (private_flags > PACKET_PRIVATE_FLAGS_MAX) {
1041 set_detailed_error("Illegal private flags value.");
1042 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1043 }
1044
1045 header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0;
1046 header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0;
1047
1048 if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) {
1049 header->is_in_fec_group = IN_FEC_GROUP;
1050 uint8 first_fec_protected_packet_offset;
1051 if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) {
1052 set_detailed_error("Unable to read first fec protected packet offset.");
1053 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1054 }
1055 if (first_fec_protected_packet_offset >= header->packet_sequence_number) {
1056 set_detailed_error("First fec protected packet offset must be less "
1057 "than the sequence number.");
1058 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1059 }
1060 header->fec_group =
1061 header->packet_sequence_number - first_fec_protected_packet_offset;
1062 }
1063
1064 header->entropy_hash = GetPacketEntropyHash(*header);
1065 // Set the last sequence number after we have decrypted the packet
1066 // so we are confident is not attacker controlled.
1067 last_sequence_number_ = header->packet_sequence_number;
1068 return true;
1069 }
1070
ProcessPacketSequenceNumber(QuicSequenceNumberLength sequence_number_length,QuicPacketSequenceNumber * sequence_number)1071 bool QuicFramer::ProcessPacketSequenceNumber(
1072 QuicSequenceNumberLength sequence_number_length,
1073 QuicPacketSequenceNumber* sequence_number) {
1074 QuicPacketSequenceNumber wire_sequence_number = 0u;
1075 if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) {
1076 return false;
1077 }
1078
1079 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1080 // in case the first guess is incorrect.
1081 *sequence_number =
1082 CalculatePacketSequenceNumberFromWire(sequence_number_length,
1083 wire_sequence_number);
1084 return true;
1085 }
1086
ProcessFrameData(const QuicPacketHeader & header)1087 bool QuicFramer::ProcessFrameData(const QuicPacketHeader& header) {
1088 if (reader_->IsDoneReading()) {
1089 set_detailed_error("Packet has no frames.");
1090 return RaiseError(QUIC_MISSING_PAYLOAD);
1091 }
1092 while (!reader_->IsDoneReading()) {
1093 uint8 frame_type;
1094 if (!reader_->ReadBytes(&frame_type, 1)) {
1095 set_detailed_error("Unable to read frame type.");
1096 return RaiseError(QUIC_INVALID_FRAME_DATA);
1097 }
1098
1099 if (frame_type & kQuicFrameTypeSpecialMask) {
1100 // Stream Frame
1101 if (frame_type & kQuicFrameTypeStreamMask) {
1102 QuicStreamFrame frame;
1103 if (!ProcessStreamFrame(frame_type, &frame)) {
1104 return RaiseError(QUIC_INVALID_STREAM_DATA);
1105 }
1106 if (!visitor_->OnStreamFrame(frame)) {
1107 DVLOG(1) << "Visitor asked to stop further processing.";
1108 // Returning true since there was no parsing error.
1109 return true;
1110 }
1111 continue;
1112 }
1113
1114 // Ack Frame
1115 if (frame_type & kQuicFrameTypeAckMask) {
1116 QuicAckFrame frame;
1117 if (!ProcessAckFrame(header, frame_type, &frame)) {
1118 return RaiseError(QUIC_INVALID_ACK_DATA);
1119 }
1120 if (!visitor_->OnAckFrame(frame)) {
1121 DVLOG(1) << "Visitor asked to stop further processing.";
1122 // Returning true since there was no parsing error.
1123 return true;
1124 }
1125 continue;
1126 }
1127
1128 // Congestion Feedback Frame
1129 if (frame_type & kQuicFrameTypeCongestionFeedbackMask) {
1130 QuicCongestionFeedbackFrame frame;
1131 if (!ProcessQuicCongestionFeedbackFrame(&frame)) {
1132 return RaiseError(QUIC_INVALID_CONGESTION_FEEDBACK_DATA);
1133 }
1134 if (!visitor_->OnCongestionFeedbackFrame(frame)) {
1135 DVLOG(1) << "Visitor asked to stop further processing.";
1136 // Returning true since there was no parsing error.
1137 return true;
1138 }
1139 continue;
1140 }
1141
1142 // This was a special frame type that did not match any
1143 // of the known ones. Error.
1144 set_detailed_error("Illegal frame type.");
1145 DLOG(WARNING) << "Illegal frame type: "
1146 << static_cast<int>(frame_type);
1147 return RaiseError(QUIC_INVALID_FRAME_DATA);
1148 }
1149
1150 switch (frame_type) {
1151 case PADDING_FRAME:
1152 // We're done with the packet.
1153 return true;
1154
1155 case RST_STREAM_FRAME: {
1156 QuicRstStreamFrame frame;
1157 if (!ProcessRstStreamFrame(&frame)) {
1158 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
1159 }
1160 if (!visitor_->OnRstStreamFrame(frame)) {
1161 DVLOG(1) << "Visitor asked to stop further processing.";
1162 // Returning true since there was no parsing error.
1163 return true;
1164 }
1165 continue;
1166 }
1167
1168 case CONNECTION_CLOSE_FRAME: {
1169 QuicConnectionCloseFrame frame;
1170 if (!ProcessConnectionCloseFrame(&frame)) {
1171 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
1172 }
1173
1174 if (!visitor_->OnConnectionCloseFrame(frame)) {
1175 DVLOG(1) << "Visitor asked to stop further processing.";
1176 // Returning true since there was no parsing error.
1177 return true;
1178 }
1179 continue;
1180 }
1181
1182 case GOAWAY_FRAME: {
1183 QuicGoAwayFrame goaway_frame;
1184 if (!ProcessGoAwayFrame(&goaway_frame)) {
1185 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
1186 }
1187 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
1188 DVLOG(1) << "Visitor asked to stop further processing.";
1189 // Returning true since there was no parsing error.
1190 return true;
1191 }
1192 continue;
1193 }
1194
1195 case WINDOW_UPDATE_FRAME: {
1196 QuicWindowUpdateFrame window_update_frame;
1197 if (!ProcessWindowUpdateFrame(&window_update_frame)) {
1198 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
1199 }
1200 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
1201 DVLOG(1) << "Visitor asked to stop further processing.";
1202 // Returning true since there was no parsing error.
1203 return true;
1204 }
1205 continue;
1206 }
1207
1208 case BLOCKED_FRAME: {
1209 QuicBlockedFrame blocked_frame;
1210 if (!ProcessBlockedFrame(&blocked_frame)) {
1211 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
1212 }
1213 if (!visitor_->OnBlockedFrame(blocked_frame)) {
1214 DVLOG(1) << "Visitor asked to stop further processing.";
1215 // Returning true since there was no parsing error.
1216 return true;
1217 }
1218 continue;
1219 }
1220
1221 case STOP_WAITING_FRAME: {
1222 if (quic_version_ <= QUIC_VERSION_15) {
1223 LOG(DFATAL) << "Trying to read a StopWaiting in "
1224 << QuicVersionToString(quic_version_);
1225 return RaiseError(QUIC_INTERNAL_ERROR);
1226 }
1227 QuicStopWaitingFrame stop_waiting_frame;
1228 if (!ProcessStopWaitingFrame(header, &stop_waiting_frame)) {
1229 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
1230 }
1231 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
1232 DVLOG(1) << "Visitor asked to stop further processing.";
1233 // Returning true since there was no parsing error.
1234 return true;
1235 }
1236 continue;
1237 }
1238 case PING_FRAME: {
1239 if (quic_version_ <= QUIC_VERSION_17) {
1240 LOG(DFATAL) << "Trying to read a Ping in "
1241 << QuicVersionToString(quic_version_);
1242 return RaiseError(QUIC_INTERNAL_ERROR);
1243 }
1244 // Ping has no payload.
1245 QuicPingFrame ping_frame;
1246 if (!visitor_->OnPingFrame(ping_frame)) {
1247 DVLOG(1) << "Visitor asked to stop further processing.";
1248 // Returning true since there was no parsing error.
1249 return true;
1250 }
1251 continue;
1252 }
1253
1254 default:
1255 set_detailed_error("Illegal frame type.");
1256 DLOG(WARNING) << "Illegal frame type: "
1257 << static_cast<int>(frame_type);
1258 return RaiseError(QUIC_INVALID_FRAME_DATA);
1259 }
1260 }
1261
1262 return true;
1263 }
1264
ProcessStreamFrame(uint8 frame_type,QuicStreamFrame * frame)1265 bool QuicFramer::ProcessStreamFrame(uint8 frame_type,
1266 QuicStreamFrame* frame) {
1267 uint8 stream_flags = frame_type;
1268
1269 stream_flags &= ~kQuicFrameTypeStreamMask;
1270
1271 // Read from right to left: StreamID, Offset, Data Length, Fin.
1272 const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
1273 stream_flags >>= kQuicStreamIdShift;
1274
1275 uint8 offset_length = (stream_flags & kQuicStreamOffsetMask);
1276 // There is no encoding for 1 byte, only 0 and 2 through 8.
1277 if (offset_length > 0) {
1278 offset_length += 1;
1279 }
1280 stream_flags >>= kQuicStreamOffsetShift;
1281
1282 bool has_data_length =
1283 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
1284 stream_flags >>= kQuicStreamDataLengthShift;
1285
1286 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
1287
1288 frame->stream_id = 0;
1289 if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) {
1290 set_detailed_error("Unable to read stream_id.");
1291 return false;
1292 }
1293
1294 frame->offset = 0;
1295 if (!reader_->ReadBytes(&frame->offset, offset_length)) {
1296 set_detailed_error("Unable to read offset.");
1297 return false;
1298 }
1299
1300 StringPiece frame_data;
1301 if (has_data_length) {
1302 if (!reader_->ReadStringPiece16(&frame_data)) {
1303 set_detailed_error("Unable to read frame data.");
1304 return false;
1305 }
1306 } else {
1307 if (!reader_->ReadStringPiece(&frame_data, reader_->BytesRemaining())) {
1308 set_detailed_error("Unable to read frame data.");
1309 return false;
1310 }
1311 }
1312 // Point frame to the right data.
1313 frame->data.Clear();
1314 if (!frame_data.empty()) {
1315 frame->data.Append(const_cast<char*>(frame_data.data()), frame_data.size());
1316 }
1317
1318 return true;
1319 }
1320
ProcessAckFrame(const QuicPacketHeader & header,uint8 frame_type,QuicAckFrame * frame)1321 bool QuicFramer::ProcessAckFrame(const QuicPacketHeader& header,
1322 uint8 frame_type,
1323 QuicAckFrame* frame) {
1324 if (quic_version_ <= QUIC_VERSION_15) {
1325 if (!ProcessStopWaitingFrame(header, &frame->sent_info)) {
1326 return false;
1327 }
1328 }
1329 if (!ProcessReceivedInfo(frame_type, &frame->received_info)) {
1330 return false;
1331 }
1332 return true;
1333 }
1334
ProcessReceivedInfo(uint8 frame_type,ReceivedPacketInfo * received_info)1335 bool QuicFramer::ProcessReceivedInfo(uint8 frame_type,
1336 ReceivedPacketInfo* received_info) {
1337 // Determine the three lengths from the frame type: largest observed length,
1338 // missing sequence number length, and missing range length.
1339 const QuicSequenceNumberLength missing_sequence_number_length =
1340 ReadSequenceNumberLength(frame_type);
1341 frame_type >>= kQuicSequenceNumberLengthShift;
1342 const QuicSequenceNumberLength largest_observed_sequence_number_length =
1343 ReadSequenceNumberLength(frame_type);
1344 frame_type >>= kQuicSequenceNumberLengthShift;
1345 received_info->is_truncated = frame_type & kQuicAckTruncatedMask;
1346 frame_type >>= kQuicAckTruncatedShift;
1347 bool has_nacks = frame_type & kQuicHasNacksMask;
1348
1349 if (!reader_->ReadBytes(&received_info->entropy_hash, 1)) {
1350 set_detailed_error("Unable to read entropy hash for received packets.");
1351 return false;
1352 }
1353
1354 if (!reader_->ReadBytes(&received_info->largest_observed,
1355 largest_observed_sequence_number_length)) {
1356 set_detailed_error("Unable to read largest observed.");
1357 return false;
1358 }
1359
1360 uint64 delta_time_largest_observed_us;
1361 if (!reader_->ReadUFloat16(&delta_time_largest_observed_us)) {
1362 set_detailed_error("Unable to read delta time largest observed.");
1363 return false;
1364 }
1365
1366 if (delta_time_largest_observed_us == kUFloat16MaxValue) {
1367 received_info->delta_time_largest_observed = QuicTime::Delta::Infinite();
1368 } else {
1369 received_info->delta_time_largest_observed =
1370 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us);
1371 }
1372
1373 if (!has_nacks) {
1374 return true;
1375 }
1376
1377 uint8 num_missing_ranges;
1378 if (!reader_->ReadBytes(&num_missing_ranges, 1)) {
1379 set_detailed_error("Unable to read num missing packet ranges.");
1380 return false;
1381 }
1382
1383 QuicPacketSequenceNumber last_sequence_number =
1384 received_info->largest_observed;
1385 for (size_t i = 0; i < num_missing_ranges; ++i) {
1386 QuicPacketSequenceNumber missing_delta = 0;
1387 if (!reader_->ReadBytes(&missing_delta, missing_sequence_number_length)) {
1388 set_detailed_error("Unable to read missing sequence number delta.");
1389 return false;
1390 }
1391 last_sequence_number -= missing_delta;
1392 QuicPacketSequenceNumber range_length = 0;
1393 if (!reader_->ReadBytes(&range_length, PACKET_1BYTE_SEQUENCE_NUMBER)) {
1394 set_detailed_error("Unable to read missing sequence number range.");
1395 return false;
1396 }
1397 for (size_t i = 0; i <= range_length; ++i) {
1398 received_info->missing_packets.insert(last_sequence_number - i);
1399 }
1400 // Subtract an extra 1 to ensure ranges are represented efficiently and
1401 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1402 // to represent an adjacent nack range.
1403 last_sequence_number -= (range_length + 1);
1404 }
1405
1406 // Parse the revived packets list.
1407 uint8 num_revived_packets;
1408 if (!reader_->ReadBytes(&num_revived_packets, 1)) {
1409 set_detailed_error("Unable to read num revived packets.");
1410 return false;
1411 }
1412
1413 for (size_t i = 0; i < num_revived_packets; ++i) {
1414 QuicPacketSequenceNumber revived_packet = 0;
1415 if (!reader_->ReadBytes(&revived_packet,
1416 largest_observed_sequence_number_length)) {
1417 set_detailed_error("Unable to read revived packet.");
1418 return false;
1419 }
1420
1421 received_info->revived_packets.insert(revived_packet);
1422 }
1423
1424 return true;
1425 }
1426
ProcessStopWaitingFrame(const QuicPacketHeader & header,QuicStopWaitingFrame * stop_waiting)1427 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader& header,
1428 QuicStopWaitingFrame* stop_waiting) {
1429 if (!reader_->ReadBytes(&stop_waiting->entropy_hash, 1)) {
1430 set_detailed_error("Unable to read entropy hash for sent packets.");
1431 return false;
1432 }
1433
1434 QuicPacketSequenceNumber least_unacked_delta = 0;
1435 if (!reader_->ReadBytes(&least_unacked_delta,
1436 header.public_header.sequence_number_length)) {
1437 set_detailed_error("Unable to read least unacked delta.");
1438 return false;
1439 }
1440 DCHECK_GE(header.packet_sequence_number, least_unacked_delta);
1441 stop_waiting->least_unacked =
1442 header.packet_sequence_number - least_unacked_delta;
1443
1444 return true;
1445 }
1446
ProcessQuicCongestionFeedbackFrame(QuicCongestionFeedbackFrame * frame)1447 bool QuicFramer::ProcessQuicCongestionFeedbackFrame(
1448 QuicCongestionFeedbackFrame* frame) {
1449 uint8 feedback_type;
1450 if (!reader_->ReadBytes(&feedback_type, 1)) {
1451 set_detailed_error("Unable to read congestion feedback type.");
1452 return false;
1453 }
1454 frame->type =
1455 static_cast<CongestionFeedbackType>(feedback_type);
1456
1457 switch (frame->type) {
1458 case kInterArrival: {
1459 CongestionFeedbackMessageInterArrival* inter_arrival =
1460 &frame->inter_arrival;
1461 uint8 num_received_packets;
1462 if (!reader_->ReadBytes(&num_received_packets, 1)) {
1463 set_detailed_error("Unable to read num received packets.");
1464 return false;
1465 }
1466
1467 if (num_received_packets > 0u) {
1468 uint64 smallest_received;
1469 if (!ProcessPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
1470 &smallest_received)) {
1471 set_detailed_error("Unable to read smallest received.");
1472 return false;
1473 }
1474
1475 uint64 time_received_us;
1476 if (!reader_->ReadUInt64(&time_received_us)) {
1477 set_detailed_error("Unable to read time received.");
1478 return false;
1479 }
1480 QuicTime time_received = creation_time_.Add(
1481 QuicTime::Delta::FromMicroseconds(time_received_us));
1482
1483 inter_arrival->received_packet_times.insert(
1484 make_pair(smallest_received, time_received));
1485
1486 for (uint8 i = 0; i < num_received_packets - 1; ++i) {
1487 uint16 sequence_delta;
1488 if (!reader_->ReadUInt16(&sequence_delta)) {
1489 set_detailed_error(
1490 "Unable to read sequence delta in received packets.");
1491 return false;
1492 }
1493
1494 int32 time_delta_us;
1495 if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) {
1496 set_detailed_error(
1497 "Unable to read time delta in received packets.");
1498 return false;
1499 }
1500 QuicPacketSequenceNumber packet = smallest_received + sequence_delta;
1501 inter_arrival->received_packet_times.insert(
1502 make_pair(packet, time_received.Add(
1503 QuicTime::Delta::FromMicroseconds(time_delta_us))));
1504 }
1505 }
1506 break;
1507 }
1508 case kFixRate: {
1509 uint32 bitrate = 0;
1510 if (!reader_->ReadUInt32(&bitrate)) {
1511 set_detailed_error("Unable to read bitrate.");
1512 return false;
1513 }
1514 frame->fix_rate.bitrate = QuicBandwidth::FromBytesPerSecond(bitrate);
1515 break;
1516 }
1517 case kTCP: {
1518 CongestionFeedbackMessageTCP* tcp = &frame->tcp;
1519 // TODO(ianswett): Remove receive window, since it's constant.
1520 uint16 receive_window = 0;
1521 if (!reader_->ReadUInt16(&receive_window)) {
1522 set_detailed_error("Unable to read receive window.");
1523 return false;
1524 }
1525 // Simple bit packing, don't send the 4 least significant bits.
1526 tcp->receive_window = static_cast<QuicByteCount>(receive_window) << 4;
1527 break;
1528 }
1529 default:
1530 set_detailed_error("Illegal congestion feedback type.");
1531 DLOG(WARNING) << "Illegal congestion feedback type: "
1532 << frame->type;
1533 return RaiseError(QUIC_INVALID_FRAME_DATA);
1534 }
1535
1536 return true;
1537 }
1538
ProcessRstStreamFrame(QuicRstStreamFrame * frame)1539 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) {
1540 if (!reader_->ReadUInt32(&frame->stream_id)) {
1541 set_detailed_error("Unable to read stream_id.");
1542 return false;
1543 }
1544
1545 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1546 set_detailed_error("Unable to read rst stream sent byte offset.");
1547 return false;
1548 }
1549
1550 uint32 error_code;
1551 if (!reader_->ReadUInt32(&error_code)) {
1552 set_detailed_error("Unable to read rst stream error code.");
1553 return false;
1554 }
1555
1556 if (error_code >= QUIC_STREAM_LAST_ERROR ||
1557 error_code < QUIC_STREAM_NO_ERROR) {
1558 set_detailed_error("Invalid rst stream error code.");
1559 return false;
1560 }
1561
1562 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
1563
1564 StringPiece error_details;
1565 if (!reader_->ReadStringPiece16(&error_details)) {
1566 set_detailed_error("Unable to read rst stream error details.");
1567 return false;
1568 }
1569 frame->error_details = error_details.as_string();
1570
1571 return true;
1572 }
1573
ProcessConnectionCloseFrame(QuicConnectionCloseFrame * frame)1574 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) {
1575 uint32 error_code;
1576 if (!reader_->ReadUInt32(&error_code)) {
1577 set_detailed_error("Unable to read connection close error code.");
1578 return false;
1579 }
1580
1581 if (error_code >= QUIC_LAST_ERROR ||
1582 error_code < QUIC_NO_ERROR) {
1583 set_detailed_error("Invalid error code.");
1584 return false;
1585 }
1586
1587 frame->error_code = static_cast<QuicErrorCode>(error_code);
1588
1589 StringPiece error_details;
1590 if (!reader_->ReadStringPiece16(&error_details)) {
1591 set_detailed_error("Unable to read connection close error details.");
1592 return false;
1593 }
1594 frame->error_details = error_details.as_string();
1595
1596 return true;
1597 }
1598
ProcessGoAwayFrame(QuicGoAwayFrame * frame)1599 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) {
1600 uint32 error_code;
1601 if (!reader_->ReadUInt32(&error_code)) {
1602 set_detailed_error("Unable to read go away error code.");
1603 return false;
1604 }
1605 frame->error_code = static_cast<QuicErrorCode>(error_code);
1606
1607 if (error_code >= QUIC_LAST_ERROR ||
1608 error_code < QUIC_NO_ERROR) {
1609 set_detailed_error("Invalid error code.");
1610 return false;
1611 }
1612
1613 uint32 stream_id;
1614 if (!reader_->ReadUInt32(&stream_id)) {
1615 set_detailed_error("Unable to read last good stream id.");
1616 return false;
1617 }
1618 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
1619
1620 StringPiece reason_phrase;
1621 if (!reader_->ReadStringPiece16(&reason_phrase)) {
1622 set_detailed_error("Unable to read goaway reason.");
1623 return false;
1624 }
1625 frame->reason_phrase = reason_phrase.as_string();
1626
1627 return true;
1628 }
1629
ProcessWindowUpdateFrame(QuicWindowUpdateFrame * frame)1630 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame) {
1631 if (!reader_->ReadUInt32(&frame->stream_id)) {
1632 set_detailed_error("Unable to read stream_id.");
1633 return false;
1634 }
1635
1636 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1637 set_detailed_error("Unable to read window byte_offset.");
1638 return false;
1639 }
1640
1641 return true;
1642 }
1643
ProcessBlockedFrame(QuicBlockedFrame * frame)1644 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame* frame) {
1645 if (!reader_->ReadUInt32(&frame->stream_id)) {
1646 set_detailed_error("Unable to read stream_id.");
1647 return false;
1648 }
1649
1650 return true;
1651 }
1652
1653 // static
GetAssociatedDataFromEncryptedPacket(const QuicEncryptedPacket & encrypted,QuicConnectionIdLength connection_id_length,bool includes_version,QuicSequenceNumberLength sequence_number_length)1654 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
1655 const QuicEncryptedPacket& encrypted,
1656 QuicConnectionIdLength connection_id_length,
1657 bool includes_version,
1658 QuicSequenceNumberLength sequence_number_length) {
1659 return StringPiece(
1660 encrypted.data() + kStartOfHashData, GetStartOfEncryptedData(
1661 connection_id_length, includes_version, sequence_number_length)
1662 - kStartOfHashData);
1663 }
1664
SetDecrypter(QuicDecrypter * decrypter,EncryptionLevel level)1665 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter,
1666 EncryptionLevel level) {
1667 DCHECK(alternative_decrypter_.get() == NULL);
1668 DCHECK_GE(level, decrypter_level_);
1669 decrypter_.reset(decrypter);
1670 decrypter_level_ = level;
1671 }
1672
SetAlternativeDecrypter(QuicDecrypter * decrypter,EncryptionLevel level,bool latch_once_used)1673 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1674 EncryptionLevel level,
1675 bool latch_once_used) {
1676 alternative_decrypter_.reset(decrypter);
1677 alternative_decrypter_level_ = level;
1678 alternative_decrypter_latch_ = latch_once_used;
1679 }
1680
decrypter() const1681 const QuicDecrypter* QuicFramer::decrypter() const {
1682 return decrypter_.get();
1683 }
1684
alternative_decrypter() const1685 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
1686 return alternative_decrypter_.get();
1687 }
1688
SetEncrypter(EncryptionLevel level,QuicEncrypter * encrypter)1689 void QuicFramer::SetEncrypter(EncryptionLevel level,
1690 QuicEncrypter* encrypter) {
1691 DCHECK_GE(level, 0);
1692 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1693 encrypter_[level].reset(encrypter);
1694 }
1695
encrypter(EncryptionLevel level) const1696 const QuicEncrypter* QuicFramer::encrypter(EncryptionLevel level) const {
1697 DCHECK_GE(level, 0);
1698 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1699 DCHECK(encrypter_[level].get() != NULL);
1700 return encrypter_[level].get();
1701 }
1702
EncryptPacket(EncryptionLevel level,QuicPacketSequenceNumber packet_sequence_number,const QuicPacket & packet)1703 QuicEncryptedPacket* QuicFramer::EncryptPacket(
1704 EncryptionLevel level,
1705 QuicPacketSequenceNumber packet_sequence_number,
1706 const QuicPacket& packet) {
1707 DCHECK(encrypter_[level].get() != NULL);
1708
1709 scoped_ptr<QuicData> out(encrypter_[level]->EncryptPacket(
1710 packet_sequence_number, packet.AssociatedData(), packet.Plaintext()));
1711 if (out.get() == NULL) {
1712 RaiseError(QUIC_ENCRYPTION_FAILURE);
1713 return NULL;
1714 }
1715 StringPiece header_data = packet.BeforePlaintext();
1716 size_t len = header_data.length() + out->length();
1717 char* buffer = new char[len];
1718 // TODO(rch): eliminate this buffer copy by passing in a buffer to Encrypt().
1719 memcpy(buffer, header_data.data(), header_data.length());
1720 memcpy(buffer + header_data.length(), out->data(), out->length());
1721 return new QuicEncryptedPacket(buffer, len, true);
1722 }
1723
GetMaxPlaintextSize(size_t ciphertext_size)1724 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
1725 // In order to keep the code simple, we don't have the current encryption
1726 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1727 size_t min_plaintext_size = ciphertext_size;
1728
1729 for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
1730 if (encrypter_[i].get() != NULL) {
1731 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
1732 if (size < min_plaintext_size) {
1733 min_plaintext_size = size;
1734 }
1735 }
1736 }
1737
1738 return min_plaintext_size;
1739 }
1740
DecryptPayload(const QuicPacketHeader & header,const QuicEncryptedPacket & packet)1741 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header,
1742 const QuicEncryptedPacket& packet) {
1743 StringPiece encrypted;
1744 if (!reader_->ReadStringPiece(&encrypted, reader_->BytesRemaining())) {
1745 return false;
1746 }
1747 DCHECK(decrypter_.get() != NULL);
1748 decrypted_.reset(decrypter_->DecryptPacket(
1749 header.packet_sequence_number,
1750 GetAssociatedDataFromEncryptedPacket(
1751 packet,
1752 header.public_header.connection_id_length,
1753 header.public_header.version_flag,
1754 header.public_header.sequence_number_length),
1755 encrypted));
1756 if (decrypted_.get() != NULL) {
1757 visitor_->OnDecryptedPacket(decrypter_level_);
1758 } else if (alternative_decrypter_.get() != NULL) {
1759 decrypted_.reset(alternative_decrypter_->DecryptPacket(
1760 header.packet_sequence_number,
1761 GetAssociatedDataFromEncryptedPacket(
1762 packet,
1763 header.public_header.connection_id_length,
1764 header.public_header.version_flag,
1765 header.public_header.sequence_number_length),
1766 encrypted));
1767 if (decrypted_.get() != NULL) {
1768 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
1769 if (alternative_decrypter_latch_) {
1770 // Switch to the alternative decrypter and latch so that we cannot
1771 // switch back.
1772 decrypter_.reset(alternative_decrypter_.release());
1773 decrypter_level_ = alternative_decrypter_level_;
1774 alternative_decrypter_level_ = ENCRYPTION_NONE;
1775 } else {
1776 // Switch the alternative decrypter so that we use it first next time.
1777 decrypter_.swap(alternative_decrypter_);
1778 EncryptionLevel level = alternative_decrypter_level_;
1779 alternative_decrypter_level_ = decrypter_level_;
1780 decrypter_level_ = level;
1781 }
1782 }
1783 }
1784
1785 if (decrypted_.get() == NULL) {
1786 DLOG(WARNING) << "DecryptPacket failed for sequence_number:"
1787 << header.packet_sequence_number;
1788 return false;
1789 }
1790
1791 reader_.reset(new QuicDataReader(decrypted_->data(), decrypted_->length()));
1792 return true;
1793 }
1794
GetAckFrameSize(const QuicAckFrame & ack,QuicSequenceNumberLength sequence_number_length)1795 size_t QuicFramer::GetAckFrameSize(
1796 const QuicAckFrame& ack,
1797 QuicSequenceNumberLength sequence_number_length) {
1798 AckFrameInfo ack_info = GetAckFrameInfo(ack);
1799 QuicSequenceNumberLength largest_observed_length =
1800 GetMinSequenceNumberLength(ack.received_info.largest_observed);
1801 QuicSequenceNumberLength missing_sequence_number_length =
1802 GetMinSequenceNumberLength(ack_info.max_delta);
1803
1804 size_t ack_size = GetMinAckFrameSize(quic_version_,
1805 sequence_number_length,
1806 largest_observed_length);
1807 if (!ack_info.nack_ranges.empty()) {
1808 ack_size += kNumberOfNackRangesSize + kNumberOfRevivedPacketsSize;
1809 ack_size += min(ack_info.nack_ranges.size(), kMaxNackRanges) *
1810 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1811 ack_size += min(ack.received_info.revived_packets.size(),
1812 kMaxRevivedPackets) * largest_observed_length;
1813 }
1814 return ack_size;
1815 }
1816
ComputeFrameLength(const QuicFrame & frame,bool last_frame_in_packet,InFecGroup is_in_fec_group,QuicSequenceNumberLength sequence_number_length)1817 size_t QuicFramer::ComputeFrameLength(
1818 const QuicFrame& frame,
1819 bool last_frame_in_packet,
1820 InFecGroup is_in_fec_group,
1821 QuicSequenceNumberLength sequence_number_length) {
1822 switch (frame.type) {
1823 case STREAM_FRAME:
1824 return GetMinStreamFrameSize(quic_version_,
1825 frame.stream_frame->stream_id,
1826 frame.stream_frame->offset,
1827 last_frame_in_packet,
1828 is_in_fec_group) +
1829 frame.stream_frame->data.TotalBufferSize();
1830 case ACK_FRAME: {
1831 return GetAckFrameSize(*frame.ack_frame, sequence_number_length);
1832 }
1833 case CONGESTION_FEEDBACK_FRAME: {
1834 size_t len = kQuicFrameTypeSize;
1835 const QuicCongestionFeedbackFrame& congestion_feedback =
1836 *frame.congestion_feedback_frame;
1837 len += 1; // Congestion feedback type.
1838
1839 switch (congestion_feedback.type) {
1840 case kInterArrival: {
1841 const CongestionFeedbackMessageInterArrival& inter_arrival =
1842 congestion_feedback.inter_arrival;
1843 len += 1; // Number received packets.
1844 if (inter_arrival.received_packet_times.size() > 0) {
1845 len += PACKET_6BYTE_SEQUENCE_NUMBER; // Smallest received.
1846 len += 8; // Time.
1847 // 2 bytes per sequence number delta plus 4 bytes per delta time.
1848 len += PACKET_6BYTE_SEQUENCE_NUMBER *
1849 (inter_arrival.received_packet_times.size() - 1);
1850 }
1851 break;
1852 }
1853 case kFixRate:
1854 len += 4; // Bitrate.
1855 break;
1856 case kTCP:
1857 len += 2; // Receive window.
1858 break;
1859 default:
1860 set_detailed_error("Illegal feedback type.");
1861 DVLOG(1) << "Illegal feedback type: " << congestion_feedback.type;
1862 break;
1863 }
1864 return len;
1865 }
1866 case STOP_WAITING_FRAME:
1867 return GetStopWaitingFrameSize(sequence_number_length);
1868 case PING_FRAME:
1869 // Ping has no payload.
1870 return kQuicFrameTypeSize;
1871 case RST_STREAM_FRAME:
1872 return GetMinRstStreamFrameSize(quic_version_) +
1873 frame.rst_stream_frame->error_details.size();
1874 case CONNECTION_CLOSE_FRAME:
1875 return GetMinConnectionCloseFrameSize() +
1876 frame.connection_close_frame->error_details.size();
1877 case GOAWAY_FRAME:
1878 return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size();
1879 case WINDOW_UPDATE_FRAME:
1880 return GetWindowUpdateFrameSize();
1881 case BLOCKED_FRAME:
1882 return GetBlockedFrameSize();
1883 case PADDING_FRAME:
1884 DCHECK(false);
1885 return 0;
1886 case NUM_FRAME_TYPES:
1887 DCHECK(false);
1888 return 0;
1889 }
1890
1891 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1892 DCHECK(false);
1893 return 0;
1894 }
1895
AppendTypeByte(const QuicFrame & frame,bool no_stream_frame_length,QuicDataWriter * writer)1896 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
1897 bool no_stream_frame_length,
1898 QuicDataWriter* writer) {
1899 uint8 type_byte = 0;
1900 switch (frame.type) {
1901 case STREAM_FRAME: {
1902 if (frame.stream_frame == NULL) {
1903 LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame.";
1904 }
1905 // Fin bit.
1906 type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0;
1907
1908 // Data Length bit.
1909 type_byte <<= kQuicStreamDataLengthShift;
1910 type_byte |= no_stream_frame_length ? 0: kQuicStreamDataLengthMask;
1911
1912 // Offset 3 bits.
1913 type_byte <<= kQuicStreamOffsetShift;
1914 const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset);
1915 if (offset_len > 0) {
1916 type_byte |= offset_len - 1;
1917 }
1918
1919 // stream id 2 bits.
1920 type_byte <<= kQuicStreamIdShift;
1921 type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1;
1922 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
1923 break;
1924 }
1925 case ACK_FRAME:
1926 return true;
1927 case CONGESTION_FEEDBACK_FRAME: {
1928 // TODO(ianswett): Use extra 5 bits in the congestion feedback framing.
1929 type_byte = kQuicFrameTypeCongestionFeedbackMask;
1930 break;
1931 }
1932 default:
1933 type_byte = frame.type;
1934 break;
1935 }
1936
1937 return writer->WriteUInt8(type_byte);
1938 }
1939
1940 // static
AppendPacketSequenceNumber(QuicSequenceNumberLength sequence_number_length,QuicPacketSequenceNumber packet_sequence_number,QuicDataWriter * writer)1941 bool QuicFramer::AppendPacketSequenceNumber(
1942 QuicSequenceNumberLength sequence_number_length,
1943 QuicPacketSequenceNumber packet_sequence_number,
1944 QuicDataWriter* writer) {
1945 // Ensure the entire sequence number can be written.
1946 if (writer->capacity() - writer->length() <
1947 static_cast<size_t>(sequence_number_length)) {
1948 return false;
1949 }
1950 switch (sequence_number_length) {
1951 case PACKET_1BYTE_SEQUENCE_NUMBER:
1952 return writer->WriteUInt8(
1953 packet_sequence_number & k1ByteSequenceNumberMask);
1954 break;
1955 case PACKET_2BYTE_SEQUENCE_NUMBER:
1956 return writer->WriteUInt16(
1957 packet_sequence_number & k2ByteSequenceNumberMask);
1958 break;
1959 case PACKET_4BYTE_SEQUENCE_NUMBER:
1960 return writer->WriteUInt32(
1961 packet_sequence_number & k4ByteSequenceNumberMask);
1962 break;
1963 case PACKET_6BYTE_SEQUENCE_NUMBER:
1964 return writer->WriteUInt48(
1965 packet_sequence_number & k6ByteSequenceNumberMask);
1966 break;
1967 default:
1968 DCHECK(false) << "sequence_number_length: " << sequence_number_length;
1969 return false;
1970 }
1971 }
1972
AppendStreamFrame(const QuicStreamFrame & frame,bool no_stream_frame_length,QuicDataWriter * writer)1973 bool QuicFramer::AppendStreamFrame(
1974 const QuicStreamFrame& frame,
1975 bool no_stream_frame_length,
1976 QuicDataWriter* writer) {
1977 if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) {
1978 LOG(DFATAL) << "Writing stream id size failed.";
1979 return false;
1980 }
1981 if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) {
1982 LOG(DFATAL) << "Writing offset size failed.";
1983 return false;
1984 }
1985 if (!no_stream_frame_length) {
1986 if (!writer->WriteUInt16(frame.data.TotalBufferSize())) {
1987 LOG(DFATAL) << "Writing stream frame length failed";
1988 return false;
1989 }
1990 }
1991
1992 if (!writer->WriteIOVector(frame.data)) {
1993 LOG(DFATAL) << "Writing frame data failed.";
1994 return false;
1995 }
1996 return true;
1997 }
1998
1999 // static
set_version(const QuicVersion version)2000 void QuicFramer::set_version(const QuicVersion version) {
2001 DCHECK(IsSupportedVersion(version)) << QuicVersionToString(version);
2002 quic_version_ = version;
2003 }
2004
AppendAckFrameAndTypeByte(const QuicPacketHeader & header,const QuicAckFrame & frame,QuicDataWriter * writer)2005 bool QuicFramer::AppendAckFrameAndTypeByte(
2006 const QuicPacketHeader& header,
2007 const QuicAckFrame& frame,
2008 QuicDataWriter* writer) {
2009 AckFrameInfo ack_info = GetAckFrameInfo(frame);
2010 QuicPacketSequenceNumber ack_largest_observed =
2011 frame.received_info.largest_observed;
2012 QuicSequenceNumberLength largest_observed_length =
2013 GetMinSequenceNumberLength(ack_largest_observed);
2014 QuicSequenceNumberLength missing_sequence_number_length =
2015 GetMinSequenceNumberLength(ack_info.max_delta);
2016 // Determine whether we need to truncate ranges.
2017 size_t available_range_bytes = writer->capacity() - writer->length() -
2018 kNumberOfRevivedPacketsSize - kNumberOfNackRangesSize -
2019 GetMinAckFrameSize(quic_version_,
2020 header.public_header.sequence_number_length,
2021 largest_observed_length);
2022 size_t max_num_ranges = available_range_bytes /
2023 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
2024 max_num_ranges = min(kMaxNackRanges, max_num_ranges);
2025 bool truncated = ack_info.nack_ranges.size() > max_num_ranges;
2026 DVLOG_IF(1, truncated) << "Truncating ack from "
2027 << ack_info.nack_ranges.size() << " ranges to "
2028 << max_num_ranges;
2029 // Write out the type byte by setting the low order bits and doing shifts
2030 // to make room for the next bit flags to be set.
2031 // Whether there are any nacks.
2032 uint8 type_byte = ack_info.nack_ranges.empty() ? 0 : kQuicHasNacksMask;
2033
2034 // truncating bit.
2035 type_byte <<= kQuicAckTruncatedShift;
2036 type_byte |= truncated ? kQuicAckTruncatedMask : 0;
2037
2038 // Largest observed sequence number length.
2039 type_byte <<= kQuicSequenceNumberLengthShift;
2040 type_byte |= GetSequenceNumberFlags(largest_observed_length);
2041
2042 // Missing sequence number length.
2043 type_byte <<= kQuicSequenceNumberLengthShift;
2044 type_byte |= GetSequenceNumberFlags(missing_sequence_number_length);
2045
2046 type_byte |= kQuicFrameTypeAckMask;
2047
2048 if (!writer->WriteUInt8(type_byte)) {
2049 return false;
2050 }
2051
2052 if (quic_version_ <= QUIC_VERSION_15) {
2053 if (!AppendStopWaitingFrame(header, frame.sent_info, writer)) {
2054 return false;
2055 }
2056 }
2057
2058 const ReceivedPacketInfo& received_info = frame.received_info;
2059 QuicPacketEntropyHash ack_entropy_hash = received_info.entropy_hash;
2060 NackRangeMap::reverse_iterator ack_iter = ack_info.nack_ranges.rbegin();
2061 if (truncated) {
2062 // Skip the nack ranges which the truncated ack won't include and set
2063 // a correct largest observed for the truncated ack.
2064 for (size_t i = 1; i < (ack_info.nack_ranges.size() - max_num_ranges);
2065 ++i) {
2066 ++ack_iter;
2067 }
2068 // If the last range is followed by acks, include them.
2069 // If the last range is followed by another range, specify the end of the
2070 // range as the largest_observed.
2071 ack_largest_observed = ack_iter->first - 1;
2072 // Also update the entropy so it matches the largest observed.
2073 ack_entropy_hash = entropy_calculator_->EntropyHash(ack_largest_observed);
2074 ++ack_iter;
2075 }
2076
2077 if (!writer->WriteUInt8(ack_entropy_hash)) {
2078 return false;
2079 }
2080
2081 if (!AppendPacketSequenceNumber(largest_observed_length,
2082 ack_largest_observed, writer)) {
2083 return false;
2084 }
2085
2086 uint64 delta_time_largest_observed_us = kUFloat16MaxValue;
2087 if (!received_info.delta_time_largest_observed.IsInfinite()) {
2088 DCHECK_LE(0u,
2089 frame.received_info.delta_time_largest_observed.ToMicroseconds());
2090 delta_time_largest_observed_us =
2091 received_info.delta_time_largest_observed.ToMicroseconds();
2092 }
2093
2094 if (!writer->WriteUFloat16(delta_time_largest_observed_us)) {
2095 return false;
2096 }
2097
2098 if (ack_info.nack_ranges.empty()) {
2099 return true;
2100 }
2101
2102 const uint8 num_missing_ranges =
2103 min(ack_info.nack_ranges.size(), max_num_ranges);
2104 if (!writer->WriteBytes(&num_missing_ranges, 1)) {
2105 return false;
2106 }
2107
2108 int num_ranges_written = 0;
2109 QuicPacketSequenceNumber last_sequence_written = ack_largest_observed;
2110 for (; ack_iter != ack_info.nack_ranges.rend(); ++ack_iter) {
2111 // Calculate the delta to the last number in the range.
2112 QuicPacketSequenceNumber missing_delta =
2113 last_sequence_written - (ack_iter->first + ack_iter->second);
2114 if (!AppendPacketSequenceNumber(missing_sequence_number_length,
2115 missing_delta, writer)) {
2116 return false;
2117 }
2118 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER,
2119 ack_iter->second, writer)) {
2120 return false;
2121 }
2122 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2123 last_sequence_written = ack_iter->first - 1;
2124 ++num_ranges_written;
2125 }
2126 DCHECK_EQ(num_missing_ranges, num_ranges_written);
2127
2128 // Append revived packets.
2129 // If not all the revived packets fit, only mention the ones that do.
2130 uint8 num_revived_packets = min(received_info.revived_packets.size(),
2131 kMaxRevivedPackets);
2132 num_revived_packets = min(
2133 static_cast<size_t>(num_revived_packets),
2134 (writer->capacity() - writer->length()) / largest_observed_length);
2135 if (!writer->WriteBytes(&num_revived_packets, 1)) {
2136 return false;
2137 }
2138
2139 SequenceNumberSet::const_iterator iter =
2140 received_info.revived_packets.begin();
2141 for (int i = 0; i < num_revived_packets; ++i, ++iter) {
2142 LOG_IF(DFATAL, !ContainsKey(received_info.missing_packets, *iter));
2143 if (!AppendPacketSequenceNumber(largest_observed_length,
2144 *iter, writer)) {
2145 return false;
2146 }
2147 }
2148
2149 return true;
2150 }
2151
AppendCongestionFeedbackFrame(const QuicCongestionFeedbackFrame & frame,QuicDataWriter * writer)2152 bool QuicFramer::AppendCongestionFeedbackFrame(
2153 const QuicCongestionFeedbackFrame& frame,
2154 QuicDataWriter* writer) {
2155 if (!writer->WriteBytes(&frame.type, 1)) {
2156 return false;
2157 }
2158
2159 switch (frame.type) {
2160 case kInterArrival: {
2161 const CongestionFeedbackMessageInterArrival& inter_arrival =
2162 frame.inter_arrival;
2163 DCHECK_GE(numeric_limits<uint8>::max(),
2164 inter_arrival.received_packet_times.size());
2165 if (inter_arrival.received_packet_times.size() >
2166 numeric_limits<uint8>::max()) {
2167 return false;
2168 }
2169 // TODO(ianswett): Make num_received_packets a varint.
2170 uint8 num_received_packets =
2171 inter_arrival.received_packet_times.size();
2172 if (!writer->WriteBytes(&num_received_packets, 1)) {
2173 return false;
2174 }
2175 if (num_received_packets > 0) {
2176 TimeMap::const_iterator it =
2177 inter_arrival.received_packet_times.begin();
2178
2179 QuicPacketSequenceNumber lowest_sequence = it->first;
2180 if (!AppendPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
2181 lowest_sequence, writer)) {
2182 return false;
2183 }
2184
2185 QuicTime lowest_time = it->second;
2186 if (!writer->WriteUInt64(
2187 lowest_time.Subtract(creation_time_).ToMicroseconds())) {
2188 return false;
2189 }
2190
2191 for (++it; it != inter_arrival.received_packet_times.end(); ++it) {
2192 QuicPacketSequenceNumber sequence_delta = it->first - lowest_sequence;
2193 DCHECK_GE(numeric_limits<uint16>::max(), sequence_delta);
2194 if (sequence_delta > numeric_limits<uint16>::max()) {
2195 return false;
2196 }
2197 if (!writer->WriteUInt16(static_cast<uint16>(sequence_delta))) {
2198 return false;
2199 }
2200
2201 int32 time_delta_us =
2202 it->second.Subtract(lowest_time).ToMicroseconds();
2203 if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) {
2204 return false;
2205 }
2206 }
2207 }
2208 break;
2209 }
2210 case kFixRate: {
2211 const CongestionFeedbackMessageFixRate& fix_rate =
2212 frame.fix_rate;
2213 if (!writer->WriteUInt32(fix_rate.bitrate.ToBytesPerSecond())) {
2214 return false;
2215 }
2216 break;
2217 }
2218 case kTCP: {
2219 const CongestionFeedbackMessageTCP& tcp = frame.tcp;
2220 DCHECK_LE(tcp.receive_window, 1u << 20);
2221 // Simple bit packing, don't send the 4 least significant bits.
2222 uint16 receive_window = static_cast<uint16>(tcp.receive_window >> 4);
2223 if (!writer->WriteUInt16(receive_window)) {
2224 return false;
2225 }
2226 break;
2227 }
2228 default:
2229 return false;
2230 }
2231
2232 return true;
2233 }
2234
AppendStopWaitingFrame(const QuicPacketHeader & header,const QuicStopWaitingFrame & frame,QuicDataWriter * writer)2235 bool QuicFramer::AppendStopWaitingFrame(
2236 const QuicPacketHeader& header,
2237 const QuicStopWaitingFrame& frame,
2238 QuicDataWriter* writer) {
2239 DCHECK_GE(header.packet_sequence_number, frame.least_unacked);
2240 const QuicPacketSequenceNumber least_unacked_delta =
2241 header.packet_sequence_number - frame.least_unacked;
2242 const QuicPacketSequenceNumber length_shift =
2243 header.public_header.sequence_number_length * 8;
2244 if (!writer->WriteUInt8(frame.entropy_hash)) {
2245 LOG(DFATAL) << " hash failed";
2246 return false;
2247 }
2248
2249 if (least_unacked_delta >> length_shift > 0) {
2250 LOG(DFATAL) << "sequence_number_length "
2251 << header.public_header.sequence_number_length
2252 << " is too small for least_unacked_delta: "
2253 << least_unacked_delta;
2254 return false;
2255 }
2256 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
2257 least_unacked_delta, writer)) {
2258 LOG(DFATAL) << " seq failed: "
2259 << header.public_header.sequence_number_length;
2260 return false;
2261 }
2262
2263 return true;
2264 }
2265
AppendRstStreamFrame(const QuicRstStreamFrame & frame,QuicDataWriter * writer)2266 bool QuicFramer::AppendRstStreamFrame(
2267 const QuicRstStreamFrame& frame,
2268 QuicDataWriter* writer) {
2269 if (!writer->WriteUInt32(frame.stream_id)) {
2270 return false;
2271 }
2272
2273 if (!writer->WriteUInt64(frame.byte_offset)) {
2274 return false;
2275 }
2276
2277 uint32 error_code = static_cast<uint32>(frame.error_code);
2278 if (!writer->WriteUInt32(error_code)) {
2279 return false;
2280 }
2281
2282 if (!writer->WriteStringPiece16(frame.error_details)) {
2283 return false;
2284 }
2285 return true;
2286 }
2287
AppendConnectionCloseFrame(const QuicConnectionCloseFrame & frame,QuicDataWriter * writer)2288 bool QuicFramer::AppendConnectionCloseFrame(
2289 const QuicConnectionCloseFrame& frame,
2290 QuicDataWriter* writer) {
2291 uint32 error_code = static_cast<uint32>(frame.error_code);
2292 if (!writer->WriteUInt32(error_code)) {
2293 return false;
2294 }
2295 if (!writer->WriteStringPiece16(frame.error_details)) {
2296 return false;
2297 }
2298 return true;
2299 }
2300
AppendGoAwayFrame(const QuicGoAwayFrame & frame,QuicDataWriter * writer)2301 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
2302 QuicDataWriter* writer) {
2303 uint32 error_code = static_cast<uint32>(frame.error_code);
2304 if (!writer->WriteUInt32(error_code)) {
2305 return false;
2306 }
2307 uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id);
2308 if (!writer->WriteUInt32(stream_id)) {
2309 return false;
2310 }
2311 if (!writer->WriteStringPiece16(frame.reason_phrase)) {
2312 return false;
2313 }
2314 return true;
2315 }
2316
AppendWindowUpdateFrame(const QuicWindowUpdateFrame & frame,QuicDataWriter * writer)2317 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
2318 QuicDataWriter* writer) {
2319 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2320 if (!writer->WriteUInt32(stream_id)) {
2321 return false;
2322 }
2323 if (!writer->WriteUInt64(frame.byte_offset)) {
2324 return false;
2325 }
2326 return true;
2327 }
2328
AppendBlockedFrame(const QuicBlockedFrame & frame,QuicDataWriter * writer)2329 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
2330 QuicDataWriter* writer) {
2331 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2332 if (!writer->WriteUInt32(stream_id)) {
2333 return false;
2334 }
2335 return true;
2336 }
2337
RaiseError(QuicErrorCode error)2338 bool QuicFramer::RaiseError(QuicErrorCode error) {
2339 DVLOG(1) << "Error detail: " << detailed_error_;
2340 set_error(error);
2341 visitor_->OnError(this);
2342 reader_.reset(NULL);
2343 return false;
2344 }
2345
2346 } // namespace net
2347