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.
5 #include "net/quic/quic_packet_creator.h"
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "net/quic/crypto/quic_random.h"
12 #include "net/quic/quic_ack_notifier.h"
13 #include "net/quic/quic_data_writer.h"
14 #include "net/quic/quic_fec_group.h"
15 #include "net/quic/quic_utils.h"
17 using base::StringPiece
;
28 // Default max packets in an FEC group.
29 static const size_t kDefaultMaxPacketsPerFecGroup
= 10;
30 // Lowest max packets in an FEC group.
31 static const size_t kLowestMaxPacketsPerFecGroup
= 2;
35 // A QuicRandom wrapper that gets a bucket of entropy and distributes it
36 // bit-by-bit. Replenishes the bucket as needed. Not thread-safe. Expose this
37 // class if single bit randomness is needed elsewhere.
38 class QuicRandomBoolSource
{
40 // random: Source of entropy. Not owned.
41 explicit QuicRandomBoolSource(QuicRandom
* random
)
46 ~QuicRandomBoolSource() {}
48 // Returns the next random bit from the bucket.
51 bit_bucket_
= random_
->RandUint64();
54 bool result
= ((bit_bucket_
& bit_mask_
) != 0);
62 // Stored random bits.
64 // The next available bit has "1" in the mask. Zero means empty bucket.
67 DISALLOW_COPY_AND_ASSIGN(QuicRandomBoolSource
);
70 QuicPacketCreator::QuicPacketCreator(QuicConnectionId connection_id
,
72 QuicRandom
* random_generator
)
73 : connection_id_(connection_id
),
74 encryption_level_(ENCRYPTION_NONE
),
76 random_bool_source_(new QuicRandomBoolSource(random_generator
)),
78 should_fec_protect_(false),
80 send_version_in_packet_(framer
->perspective() == Perspective::IS_CLIENT
),
81 max_packet_length_(0),
82 max_packets_per_fec_group_(kDefaultMaxPacketsPerFecGroup
),
83 connection_id_length_(PACKET_8BYTE_CONNECTION_ID
),
84 next_sequence_number_length_(PACKET_1BYTE_SEQUENCE_NUMBER
),
85 sequence_number_length_(next_sequence_number_length_
),
87 needs_padding_(false) {
88 SetMaxPacketLength(kDefaultMaxPacketSize
);
91 QuicPacketCreator::~QuicPacketCreator() {
94 void QuicPacketCreator::OnBuiltFecProtectedPayload(
95 const QuicPacketHeader
& header
, StringPiece payload
) {
96 if (fec_group_
.get()) {
97 DCHECK_NE(0u, header
.fec_group
);
98 fec_group_
->Update(encryption_level_
, header
, payload
);
102 void QuicPacketCreator::SetEncrypter(EncryptionLevel level
,
103 QuicEncrypter
* encrypter
) {
104 framer_
->SetEncrypter(level
, encrypter
);
105 max_plaintext_size_
= framer_
->GetMaxPlaintextSize(max_packet_length_
);
108 bool QuicPacketCreator::CanSetMaxPacketLength() const {
109 // |max_packet_length_| should not be changed mid-packet or mid-FEC group.
110 return fec_group_
.get() == nullptr && queued_frames_
.empty();
113 void QuicPacketCreator::SetMaxPacketLength(QuicByteCount length
) {
114 DCHECK(CanSetMaxPacketLength());
116 // Avoid recomputing |max_plaintext_size_| if the length does not actually
118 if (length
== max_packet_length_
) {
122 max_packet_length_
= length
;
123 max_plaintext_size_
= framer_
->GetMaxPlaintextSize(max_packet_length_
);
126 void QuicPacketCreator::set_max_packets_per_fec_group(
127 size_t max_packets_per_fec_group
) {
128 max_packets_per_fec_group_
= max(kLowestMaxPacketsPerFecGroup
,
129 max_packets_per_fec_group
);
130 DCHECK_LT(0u, max_packets_per_fec_group_
);
133 bool QuicPacketCreator::ShouldSendFec(bool force_close
) const {
134 DCHECK(!HasPendingFrames());
135 return fec_group_
.get() != nullptr && fec_group_
->NumReceivedPackets() > 0 &&
137 fec_group_
->NumReceivedPackets() >= max_packets_per_fec_group_
);
140 void QuicPacketCreator::ResetFecGroup() {
141 if (HasPendingFrames()) {
142 LOG_IF(DFATAL
, packet_size_
!= 0)
143 << "Cannot reset FEC group with pending frames.";
146 fec_group_
.reset(nullptr);
149 bool QuicPacketCreator::IsFecGroupOpen() const {
150 return fec_group_
.get() != nullptr;
153 void QuicPacketCreator::StartFecProtectingPackets() {
154 if (!IsFecEnabled()) {
155 LOG(DFATAL
) << "Cannot start FEC protection when FEC is not enabled.";
158 // TODO(jri): This currently requires that the generator flush out any
159 // pending frames when FEC protection is turned on. If current packet can be
160 // converted to an FEC protected packet, do it. This will require the
161 // generator to check if the resulting expansion still allows the incoming
162 // frame to be added to the packet.
163 if (HasPendingFrames()) {
164 LOG(DFATAL
) << "Cannot start FEC protection with pending frames.";
167 DCHECK(!should_fec_protect_
);
168 should_fec_protect_
= true;
171 void QuicPacketCreator::StopFecProtectingPackets() {
172 if (fec_group_
.get() != nullptr) {
173 LOG(DFATAL
) << "Cannot stop FEC protection with open FEC group.";
176 DCHECK(should_fec_protect_
);
177 should_fec_protect_
= false;
178 fec_group_number_
= 0;
181 bool QuicPacketCreator::IsFecProtected() const {
182 return should_fec_protect_
;
185 bool QuicPacketCreator::IsFecEnabled() const {
186 return max_packets_per_fec_group_
> 0;
189 InFecGroup
QuicPacketCreator::MaybeUpdateLengthsAndStartFec() {
190 if (fec_group_
.get() != nullptr) {
191 // Don't update any lengths when an FEC group is open, to ensure same
192 // packet header size in all packets within a group.
195 if (!queued_frames_
.empty()) {
196 // Don't change creator state if there are frames queued.
197 return NOT_IN_FEC_GROUP
;
200 // Update sequence number length only on packet and FEC group boundaries.
201 sequence_number_length_
= next_sequence_number_length_
;
203 if (!should_fec_protect_
) {
204 return NOT_IN_FEC_GROUP
;
206 // Start a new FEC group since protection is on. Set the fec group number to
207 // the sequence number of the next packet.
208 fec_group_number_
= sequence_number() + 1;
209 fec_group_
.reset(new QuicFecGroup());
213 // Stops serializing version of the protocol in packets sent after this call.
214 // A packet that is already open might send kQuicVersionSize bytes less than the
215 // maximum packet size if we stop sending version before it is serialized.
216 void QuicPacketCreator::StopSendingVersion() {
217 DCHECK(send_version_in_packet_
);
218 send_version_in_packet_
= false;
219 if (packet_size_
> 0) {
220 DCHECK_LT(kQuicVersionSize
, packet_size_
);
221 packet_size_
-= kQuicVersionSize
;
225 void QuicPacketCreator::UpdateSequenceNumberLength(
226 QuicPacketSequenceNumber least_packet_awaited_by_peer
,
227 QuicPacketCount max_packets_in_flight
) {
228 DCHECK_LE(least_packet_awaited_by_peer
, sequence_number_
+ 1);
229 // Since the packet creator will not change sequence number length mid FEC
230 // group, include the size of an FEC group to be safe.
231 const QuicPacketSequenceNumber current_delta
=
232 max_packets_per_fec_group_
+ sequence_number_
+ 1
233 - least_packet_awaited_by_peer
;
234 const uint64 delta
= max(current_delta
, max_packets_in_flight
);
235 next_sequence_number_length_
=
236 QuicFramer::GetMinSequenceNumberLength(delta
* 4);
239 bool QuicPacketCreator::HasRoomForStreamFrame(QuicStreamId id
,
240 QuicStreamOffset offset
) const {
241 // TODO(jri): This is a simple safe decision for now, but make
242 // is_in_fec_group a parameter. Same as with all public methods in
243 // QuicPacketCreator.
245 QuicFramer::GetMinStreamFrameSize(id
, offset
, true,
246 should_fec_protect_
? IN_FEC_GROUP
:
251 size_t QuicPacketCreator::StreamFramePacketOverhead(
252 QuicConnectionIdLength connection_id_length
,
253 bool include_version
,
254 QuicSequenceNumberLength sequence_number_length
,
255 QuicStreamOffset offset
,
256 InFecGroup is_in_fec_group
) {
257 return GetPacketHeaderSize(connection_id_length
, include_version
,
258 sequence_number_length
, is_in_fec_group
) +
259 // Assumes this is a stream with a single lone packet.
260 QuicFramer::GetMinStreamFrameSize(1u, offset
, true, is_in_fec_group
);
263 size_t QuicPacketCreator::CreateStreamFrame(QuicStreamId id
,
264 const QuicIOVector
& iov
,
266 QuicStreamOffset offset
,
269 scoped_ptr
<char[]>* buffer
) {
270 DCHECK_GT(max_packet_length_
, StreamFramePacketOverhead(
271 connection_id_length_
, kIncludeVersion
,
272 PACKET_6BYTE_SEQUENCE_NUMBER
, offset
, IN_FEC_GROUP
));
275 InFecGroup is_in_fec_group
= MaybeUpdateLengthsAndStartFec();
277 LOG_IF(DFATAL
, !HasRoomForStreamFrame(id
, offset
))
278 << "No room for Stream frame, BytesFree: " << BytesFree()
279 << " MinStreamFrameSize: "
280 << QuicFramer::GetMinStreamFrameSize(id
, offset
, true, is_in_fec_group
);
282 if (iov_offset
== iov
.total_length
) {
284 << "Creating a stream frame with no data or fin.";
285 // Create a new packet for the fin, if necessary.
286 *frame
= QuicFrame(new QuicStreamFrame(id
, true, offset
, StringPiece()));
290 const size_t data_size
= iov
.total_length
- iov_offset
;
291 size_t min_frame_size
= QuicFramer::GetMinStreamFrameSize(
292 id
, offset
, /* last_frame_in_packet= */ true, is_in_fec_group
);
293 size_t bytes_consumed
= min
<size_t>(BytesFree() - min_frame_size
, data_size
);
295 bool set_fin
= fin
&& bytes_consumed
== data_size
; // Last frame.
296 buffer
->reset(new char[bytes_consumed
]);
297 CopyToBuffer(iov
, iov_offset
, bytes_consumed
, buffer
->get());
298 *frame
= QuicFrame(new QuicStreamFrame(
299 id
, set_fin
, offset
, StringPiece(buffer
->get(), bytes_consumed
)));
300 return bytes_consumed
;
304 void QuicPacketCreator::CopyToBuffer(const QuicIOVector
& iov
,
309 while (iovnum
< iov
.iov_count
&& iov_offset
>= iov
.iov
[iovnum
].iov_len
) {
310 iov_offset
-= iov
.iov
[iovnum
].iov_len
;
313 while (iovnum
< iov
.iov_count
&& length
> 0) {
314 const size_t copy_len
= min(length
, iov
.iov
[iovnum
].iov_len
- iov_offset
);
315 memcpy(buffer
, static_cast<char*>(iov
.iov
[iovnum
].iov_base
) + iov_offset
,
322 LOG_IF(DFATAL
, length
> 0) << "Failed to copy entire length to buffer.";
325 SerializedPacket
QuicPacketCreator::ReserializeAllFrames(
326 const RetransmittableFrames
& frames
,
327 QuicSequenceNumberLength original_length
,
330 DCHECK(fec_group_
.get() == nullptr);
331 const QuicSequenceNumberLength saved_length
= sequence_number_length_
;
332 const QuicSequenceNumberLength saved_next_length
=
333 next_sequence_number_length_
;
334 const bool saved_should_fec_protect
= should_fec_protect_
;
335 const bool needs_padding
= needs_padding_
;
336 const EncryptionLevel default_encryption_level
= encryption_level_
;
338 // Temporarily set the sequence number length, stop FEC protection,
339 // and change the encryption level.
340 sequence_number_length_
= original_length
;
341 next_sequence_number_length_
= original_length
;
342 should_fec_protect_
= false;
343 encryption_level_
= frames
.encryption_level();
344 needs_padding_
= frames
.needs_padding();
346 // Serialize the packet and restore the FEC and sequence number length state.
347 SerializedPacket serialized_packet
=
348 SerializeAllFrames(frames
.frames(), buffer
, buffer_len
);
349 sequence_number_length_
= saved_length
;
350 next_sequence_number_length_
= saved_next_length
;
351 should_fec_protect_
= saved_should_fec_protect
;
352 needs_padding_
= needs_padding
;
353 encryption_level_
= default_encryption_level
;
355 return serialized_packet
;
358 SerializedPacket
QuicPacketCreator::SerializeAllFrames(const QuicFrames
& frames
,
361 LOG_IF(DFATAL
, !queued_frames_
.empty()) << "Frames already queued.";
362 LOG_IF(DFATAL
, frames
.empty())
363 << "Attempt to serialize empty packet";
364 for (const QuicFrame
& frame
: frames
) {
365 bool success
= AddFrame(frame
, false, false, nullptr);
368 SerializedPacket packet
= SerializePacket(buffer
, buffer_len
);
369 DCHECK(packet
.retransmittable_frames
== nullptr);
373 bool QuicPacketCreator::HasPendingFrames() const {
374 return !queued_frames_
.empty();
377 bool QuicPacketCreator::HasPendingRetransmittableFrames() const {
378 return queued_retransmittable_frames_
.get() != nullptr &&
379 !queued_retransmittable_frames_
->frames().empty();
382 size_t QuicPacketCreator::ExpansionOnNewFrame() const {
383 // If packet is FEC protected, there's no expansion.
384 if (should_fec_protect_
) {
387 // If the last frame in the packet is a stream frame, then it will expand to
388 // include the stream_length field when a new frame is added.
389 bool has_trailing_stream_frame
=
390 !queued_frames_
.empty() && queued_frames_
.back().type
== STREAM_FRAME
;
391 return has_trailing_stream_frame
? kQuicStreamPayloadLengthSize
: 0;
394 size_t QuicPacketCreator::BytesFree() const {
395 DCHECK_GE(max_plaintext_size_
, PacketSize());
396 return max_plaintext_size_
- min(max_plaintext_size_
, PacketSize()
397 + ExpansionOnNewFrame());
400 size_t QuicPacketCreator::PacketSize() const {
401 if (!queued_frames_
.empty()) {
404 if (fec_group_
.get() == nullptr) {
405 // Update sequence number length on packet and FEC boundary.
406 sequence_number_length_
= next_sequence_number_length_
;
408 packet_size_
= GetPacketHeaderSize(
409 connection_id_length_
, send_version_in_packet_
, sequence_number_length_
,
410 should_fec_protect_
? IN_FEC_GROUP
: NOT_IN_FEC_GROUP
);
414 bool QuicPacketCreator::AddSavedFrame(const QuicFrame
& frame
) {
415 return AddFrame(frame
,
416 /*save_retransmittable_frames=*/true,
417 /*needs_padding=*/false, nullptr);
420 bool QuicPacketCreator::AddSavedFrame(const QuicFrame
& frame
, char* buffer
) {
421 return AddFrame(frame
,
422 /*save_retransmittable_frames=*/true,
423 /*needs_padding=*/false, buffer
);
426 bool QuicPacketCreator::AddPaddedSavedFrame(const QuicFrame
& frame
,
428 return AddFrame(frame
,
429 /*save_retransmittable_frames=*/true,
430 /*needs_padding=*/true, buffer
);
433 SerializedPacket
QuicPacketCreator::SerializePacket(
434 char* encrypted_buffer
,
435 size_t encrypted_buffer_len
) {
436 DCHECK_LT(0u, encrypted_buffer_len
);
437 LOG_IF(DFATAL
, queued_frames_
.empty())
438 << "Attempt to serialize empty packet";
439 DCHECK_GE(sequence_number_
+ 1, fec_group_number_
);
440 QuicPacketHeader header
;
441 FillPacketHeader(should_fec_protect_
? fec_group_number_
: 0, false, &header
);
445 DCHECK_GE(max_plaintext_size_
, packet_size_
);
446 // ACK Frames will be truncated due to length only if they're the only frame
447 // in the packet, and if packet_size_ was set to max_plaintext_size_. If
448 // truncation due to length occurred, then GetSerializedFrameLength will have
449 // returned all bytes free.
450 bool possibly_truncated_by_length
= packet_size_
== max_plaintext_size_
&&
451 queued_frames_
.size() == 1 &&
452 queued_frames_
.back().type
== ACK_FRAME
;
453 char buffer
[kMaxPacketSize
];
454 scoped_ptr
<QuicPacket
> packet
;
455 // Use the packet_size_ instead of the buffer size to ensure smaller
456 // packet sizes are properly used.
457 scoped_ptr
<char[]> large_buffer
;
458 if (packet_size_
<= kMaxPacketSize
) {
460 framer_
->BuildDataPacket(header
, queued_frames_
, buffer
, packet_size_
));
462 large_buffer
.reset(new char[packet_size_
]);
463 packet
.reset(framer_
->BuildDataPacket(header
, queued_frames_
,
464 large_buffer
.get(), packet_size_
));
466 LOG_IF(DFATAL
, packet
== nullptr) << "Failed to serialize "
467 << queued_frames_
.size() << " frames.";
469 OnBuiltFecProtectedPayload(header
, packet
->FecProtectedData());
471 // Because of possible truncation, we can't be confident that our
472 // packet size calculation worked correctly.
473 if (!possibly_truncated_by_length
) {
474 DCHECK_EQ(packet_size_
, packet
->length());
476 // Immediately encrypt the packet, to ensure we don't encrypt the same packet
477 // sequence number multiple times.
478 QuicEncryptedPacket
* encrypted
=
479 framer_
->EncryptPayload(encryption_level_
, sequence_number_
, *packet
,
480 encrypted_buffer
, encrypted_buffer_len
);
481 if (encrypted
== nullptr) {
482 LOG(DFATAL
) << "Failed to encrypt packet number " << sequence_number_
;
486 // Update |needs_padding_| flag of |queued_retransmittable_frames_| here, and
487 // not in AddFrame, because when the first padded frame is added to the queue,
488 // it might not be retransmittable, and hence the flag would end up being not
490 if (queued_retransmittable_frames_
.get() != nullptr) {
491 queued_retransmittable_frames_
->set_needs_padding(needs_padding_
);
495 queued_frames_
.clear();
496 needs_padding_
= false;
497 return SerializedPacket(header
.packet_sequence_number
,
498 header
.public_header
.sequence_number_length
,
499 encrypted
, QuicFramer::GetPacketEntropyHash(header
),
500 queued_retransmittable_frames_
.release());
503 SerializedPacket
QuicPacketCreator::SerializeFec(char* buffer
,
505 DCHECK_LT(0u, buffer_len
);
506 if (fec_group_
.get() == nullptr || fec_group_
->NumReceivedPackets() <= 0) {
507 LOG(DFATAL
) << "SerializeFEC called but no group or zero packets in group.";
508 // TODO(jri): Make this a public method of framer?
511 DCHECK_EQ(0u, queued_frames_
.size());
512 QuicPacketHeader header
;
513 FillPacketHeader(fec_group_number_
, true, &header
);
514 QuicFecData fec_data
;
515 fec_data
.fec_group
= fec_group_
->min_protected_packet();
516 fec_data
.redundancy
= fec_group_
->payload_parity();
517 scoped_ptr
<QuicPacket
> packet(framer_
->BuildFecPacket(header
, fec_data
));
518 fec_group_
.reset(nullptr);
520 LOG_IF(DFATAL
, packet
== nullptr)
521 << "Failed to serialize fec packet for group:" << fec_data
.fec_group
;
522 DCHECK_GE(max_packet_length_
, packet
->length());
523 // Immediately encrypt the packet, to ensure we don't encrypt the same packet
524 // sequence number multiple times.
525 QuicEncryptedPacket
* encrypted
= framer_
->EncryptPayload(
526 encryption_level_
, sequence_number_
, *packet
, buffer
, buffer_len
);
527 if (encrypted
== nullptr) {
528 LOG(DFATAL
) << "Failed to encrypt packet number " << sequence_number_
;
531 SerializedPacket
serialized(
532 header
.packet_sequence_number
,
533 header
.public_header
.sequence_number_length
, encrypted
,
534 QuicFramer::GetPacketEntropyHash(header
), nullptr);
535 serialized
.is_fec_packet
= true;
539 QuicEncryptedPacket
* QuicPacketCreator::SerializeVersionNegotiationPacket(
540 const QuicVersionVector
& supported_versions
) {
541 DCHECK_EQ(Perspective::IS_SERVER
, framer_
->perspective());
542 QuicPacketPublicHeader header
;
543 header
.connection_id
= connection_id_
;
544 header
.reset_flag
= false;
545 header
.version_flag
= true;
546 header
.versions
= supported_versions
;
547 QuicEncryptedPacket
* encrypted
=
548 framer_
->BuildVersionNegotiationPacket(header
, supported_versions
);
550 DCHECK_GE(max_packet_length_
, encrypted
->length());
554 SerializedPacket
QuicPacketCreator::NoPacket() {
555 return SerializedPacket(0, PACKET_1BYTE_SEQUENCE_NUMBER
, nullptr, 0, nullptr);
558 void QuicPacketCreator::FillPacketHeader(QuicFecGroupNumber fec_group
,
560 QuicPacketHeader
* header
) {
561 header
->public_header
.connection_id
= connection_id_
;
562 header
->public_header
.connection_id_length
= connection_id_length_
;
563 header
->public_header
.reset_flag
= false;
564 header
->public_header
.version_flag
= send_version_in_packet_
;
565 header
->fec_flag
= fec_flag
;
566 header
->packet_sequence_number
= ++sequence_number_
;
567 header
->public_header
.sequence_number_length
= sequence_number_length_
;
568 header
->entropy_flag
= random_bool_source_
->RandBool();
569 header
->is_in_fec_group
= fec_group
== 0 ? NOT_IN_FEC_GROUP
: IN_FEC_GROUP
;
570 header
->fec_group
= fec_group
;
573 bool QuicPacketCreator::ShouldRetransmit(const QuicFrame
& frame
) {
574 switch (frame
.type
) {
577 case STOP_WAITING_FRAME
:
578 case MTU_DISCOVERY_FRAME
:
585 bool QuicPacketCreator::AddFrame(const QuicFrame
& frame
,
586 bool save_retransmittable_frames
,
589 DVLOG(1) << "Adding frame: " << frame
;
590 InFecGroup is_in_fec_group
= MaybeUpdateLengthsAndStartFec();
592 size_t frame_len
= framer_
->GetSerializedFrameLength(
593 frame
, BytesFree(), queued_frames_
.empty(), true, is_in_fec_group
,
594 sequence_number_length_
);
595 if (frame_len
== 0) {
598 DCHECK_LT(0u, packet_size_
);
599 packet_size_
+= ExpansionOnNewFrame() + frame_len
;
601 if (save_retransmittable_frames
&& ShouldRetransmit(frame
)) {
602 if (queued_retransmittable_frames_
.get() == nullptr) {
603 queued_retransmittable_frames_
.reset(
604 new RetransmittableFrames(encryption_level_
));
606 queued_frames_
.push_back(
607 queued_retransmittable_frames_
->AddFrame(frame
, buffer
));
609 queued_frames_
.push_back(frame
);
613 needs_padding_
= true;
619 void QuicPacketCreator::MaybeAddPadding() {
620 if (!needs_padding_
) {
624 if (BytesFree() == 0) {
625 // Don't pad full packets.
629 QuicPaddingFrame padding
;
630 bool success
= AddFrame(QuicFrame(&padding
), false, false, nullptr);