blob: 8267ade697c01dd6006262ea38e71028e84f35bc [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/quic_packet_generator.h"
6
7#include <cstdint>
8
9#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
10#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
11#include "net/third_party/quiche/src/quic/core/quic_types.h"
12#include "net/third_party/quiche/src/quic/core/quic_utils.h"
13#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
14#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
15#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
16#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
17
18namespace quic {
19
20QuicPacketGenerator::QuicPacketGenerator(QuicConnectionId connection_id,
21 QuicFramer* framer,
22 QuicRandom* random_generator,
23 DelegateInterface* delegate)
24 : delegate_(delegate),
25 packet_creator_(connection_id, framer, random_generator, delegate),
26 next_transmission_type_(NOT_RETRANSMISSION),
27 flusher_attached_(false),
28 should_send_ack_(false),
29 should_send_stop_waiting_(false),
30 random_generator_(random_generator),
31 fully_pad_crypto_handshake_packets_(true),
32 deprecate_ack_bundling_mode_(
33 GetQuicReloadableFlag(quic_deprecate_ack_bundling_mode)) {}
34
35QuicPacketGenerator::~QuicPacketGenerator() {
36 DeleteFrames(&queued_control_frames_);
37}
38
39void QuicPacketGenerator::SetShouldSendAck(bool also_send_stop_waiting) {
40 DCHECK(!deprecate_ack_bundling_mode_);
41 if (packet_creator_.has_ack()) {
42 // Ack already queued, nothing to do.
43 return;
44 }
45
46 if (also_send_stop_waiting && packet_creator_.has_stop_waiting()) {
47 QUIC_BUG << "Should only ever be one pending stop waiting frame.";
48 return;
49 }
50
51 should_send_ack_ = true;
52 should_send_stop_waiting_ = also_send_stop_waiting;
53 SendQueuedFrames(/*flush=*/false);
54}
55
56void QuicPacketGenerator::AddControlFrame(const QuicFrame& frame) {
57 QUIC_BUG_IF(IsControlFrame(frame.type) && !GetControlFrameId(frame))
58 << "Adding a control frame with no control frame id: " << frame;
59 if (deprecate_ack_bundling_mode_) {
60 MaybeBundleAckOpportunistically();
61 }
62 queued_control_frames_.push_back(frame);
63 SendQueuedFrames(/*flush=*/false);
64}
65
66size_t QuicPacketGenerator::ConsumeCryptoData(EncryptionLevel level,
67 size_t write_length,
68 QuicStreamOffset offset) {
69 QUIC_BUG_IF(!flusher_attached_) << "Packet flusher is not attached when "
70 "generator tries to write crypto data.";
71 if (deprecate_ack_bundling_mode_) {
72 MaybeBundleAckOpportunistically();
73 }
74 // To make reasoning about crypto frames easier, we don't combine them with
75 // other retransmittable frames in a single packet.
76 // TODO(nharper): Once we have separate packet number spaces, everything
77 // should be driven by encryption level, and we should stop flushing in this
78 // spot.
79 const bool flush = packet_creator_.HasPendingRetransmittableFrames();
80 SendQueuedFrames(flush);
81
82 size_t total_bytes_consumed = 0;
83
84 while (total_bytes_consumed < write_length) {
85 QuicFrame frame;
86 if (!packet_creator_.ConsumeCryptoData(
87 level, write_length - total_bytes_consumed,
88 offset + total_bytes_consumed, next_transmission_type_, &frame)) {
89 // The only pending data in the packet is non-retransmittable frames. I'm
90 // assuming here that they won't occupy so much of the packet that a
91 // CRYPTO frame won't fit.
92 QUIC_BUG << "Failed to ConsumeCryptoData at level " << level;
93 return 0;
94 }
95 total_bytes_consumed += frame.crypto_frame->data_length;
96
97 // TODO(ianswett): Move to having the creator flush itself when it's full.
98 packet_creator_.Flush();
99 }
100
101 // Don't allow the handshake to be bundled with other retransmittable frames.
102 SendQueuedFrames(/*flush=*/true);
103
104 return total_bytes_consumed;
105}
106
107QuicConsumedData QuicPacketGenerator::ConsumeData(QuicStreamId id,
108 size_t write_length,
109 QuicStreamOffset offset,
110 StreamSendingState state) {
111 QUIC_BUG_IF(!flusher_attached_) << "Packet flusher is not attached when "
112 "generator tries to write stream data.";
113 bool has_handshake =
114 (id == QuicUtils::GetCryptoStreamId(packet_creator_.transport_version()));
115 if (deprecate_ack_bundling_mode_) {
116 MaybeBundleAckOpportunistically();
117 }
118 bool fin = state != NO_FIN;
119 QUIC_BUG_IF(has_handshake && fin)
120 << "Handshake packets should never send a fin";
121 // To make reasoning about crypto frames easier, we don't combine them with
122 // other retransmittable frames in a single packet.
123 const bool flush =
124 has_handshake && packet_creator_.HasPendingRetransmittableFrames();
125 SendQueuedFrames(flush);
126
127 size_t total_bytes_consumed = 0;
128 bool fin_consumed = false;
129
130 if (!packet_creator_.HasRoomForStreamFrame(id, offset, write_length)) {
131 packet_creator_.Flush();
132 }
133
134 if (!fin && (write_length == 0)) {
135 QUIC_BUG << "Attempt to consume empty data without FIN.";
136 return QuicConsumedData(0, false);
137 }
138 // We determine if we can enter the fast path before executing
139 // the slow path loop.
140 bool run_fast_path = !has_handshake && state != FIN_AND_PADDING &&
141 !HasQueuedFrames() &&
142 write_length - total_bytes_consumed > kMaxPacketSize;
143
144 while (!run_fast_path && delegate_->ShouldGeneratePacket(
145 HAS_RETRANSMITTABLE_DATA,
146 has_handshake ? IS_HANDSHAKE : NOT_HANDSHAKE)) {
147 QuicFrame frame;
148 bool needs_full_padding =
149 has_handshake && fully_pad_crypto_handshake_packets_;
150
ianswette28f0222019-04-04 13:31:22 -0700151 if (!packet_creator_.ConsumeData(id, write_length - total_bytes_consumed,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500152 offset + total_bytes_consumed, fin,
153 needs_full_padding,
154 next_transmission_type_, &frame)) {
155 // The creator is always flushed if there's not enough room for a new
156 // stream frame before ConsumeData, so ConsumeData should always succeed.
157 QUIC_BUG << "Failed to ConsumeData, stream:" << id;
158 return QuicConsumedData(0, false);
159 }
160
161 // A stream frame is created and added.
162 size_t bytes_consumed = frame.stream_frame.data_length;
163 total_bytes_consumed += bytes_consumed;
164 fin_consumed = fin && total_bytes_consumed == write_length;
165 if (fin_consumed && state == FIN_AND_PADDING) {
166 AddRandomPadding();
167 }
168 DCHECK(total_bytes_consumed == write_length ||
169 (bytes_consumed > 0 && packet_creator_.HasPendingFrames()));
170
171 if (total_bytes_consumed == write_length) {
172 // We're done writing the data. Exit the loop.
173 // We don't make this a precondition because we could have 0 bytes of data
174 // if we're simply writing a fin.
175 break;
176 }
177 // TODO(ianswett): Move to having the creator flush itself when it's full.
178 packet_creator_.Flush();
179
180 run_fast_path = !has_handshake && state != FIN_AND_PADDING &&
181 !HasQueuedFrames() &&
182 write_length - total_bytes_consumed > kMaxPacketSize;
183 }
184
185 if (run_fast_path) {
186 return ConsumeDataFastPath(id, write_length, offset, state != NO_FIN,
187 total_bytes_consumed);
188 }
189
190 // Don't allow the handshake to be bundled with other retransmittable frames.
191 if (has_handshake) {
192 SendQueuedFrames(/*flush=*/true);
193 }
194
195 return QuicConsumedData(total_bytes_consumed, fin_consumed);
196}
197
198QuicConsumedData QuicPacketGenerator::ConsumeDataFastPath(
199 QuicStreamId id,
200 size_t write_length,
201 QuicStreamOffset offset,
202 bool fin,
203 size_t total_bytes_consumed) {
204 DCHECK_NE(id,
205 QuicUtils::GetCryptoStreamId(packet_creator_.transport_version()));
206
207 while (total_bytes_consumed < write_length &&
208 delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA,
209 NOT_HANDSHAKE)) {
210 // Serialize and encrypt the packet.
211 size_t bytes_consumed = 0;
212 packet_creator_.CreateAndSerializeStreamFrame(
213 id, write_length, total_bytes_consumed, offset + total_bytes_consumed,
214 fin, next_transmission_type_, &bytes_consumed);
215 total_bytes_consumed += bytes_consumed;
216 }
217
218 return QuicConsumedData(total_bytes_consumed,
219 fin && (total_bytes_consumed == write_length));
220}
221
222void QuicPacketGenerator::GenerateMtuDiscoveryPacket(QuicByteCount target_mtu) {
223 // MTU discovery frames must be sent by themselves.
224 if (!packet_creator_.CanSetMaxPacketLength()) {
225 QUIC_BUG << "MTU discovery packets should only be sent when no other "
226 << "frames needs to be sent.";
227 return;
228 }
229 const QuicByteCount current_mtu = GetCurrentMaxPacketLength();
230
231 // The MTU discovery frame is allocated on the stack, since it is going to be
232 // serialized within this function.
233 QuicMtuDiscoveryFrame mtu_discovery_frame;
234 QuicFrame frame(mtu_discovery_frame);
235
236 // Send the probe packet with the new length.
237 SetMaxPacketLength(target_mtu);
238 const bool success =
239 packet_creator_.AddPaddedSavedFrame(frame, next_transmission_type_);
240 packet_creator_.Flush();
241 // The only reason AddFrame can fail is that the packet is too full to fit in
242 // a ping. This is not possible for any sane MTU.
243 DCHECK(success);
244
245 // Reset the packet length back.
246 SetMaxPacketLength(current_mtu);
247}
248
249bool QuicPacketGenerator::CanSendWithNextPendingFrameAddition() const {
250 DCHECK(HasPendingFrames() || packet_creator_.pending_padding_bytes() > 0);
251 HasRetransmittableData retransmittable =
252 (should_send_ack_ || should_send_stop_waiting_ ||
253 packet_creator_.pending_padding_bytes() > 0)
254 ? NO_RETRANSMITTABLE_DATA
255 : HAS_RETRANSMITTABLE_DATA;
256 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
257 DCHECK(!queued_control_frames_.empty()); // These are retransmittable.
258 }
259 return delegate_->ShouldGeneratePacket(retransmittable, NOT_HANDSHAKE);
260}
261
262void QuicPacketGenerator::SendQueuedFrames(bool flush) {
263 // Only add pending frames if we are SURE we can then send the whole packet.
264 while (HasPendingFrames() &&
265 (flush || CanSendWithNextPendingFrameAddition())) {
266 bool first_frame = packet_creator_.CanSetMaxPacketLength();
267 if (!AddNextPendingFrame() && first_frame) {
268 // A single frame cannot fit into the packet, tear down the connection.
269 QUIC_BUG << "A single frame cannot fit into packet."
270 << " should_send_ack: " << should_send_ack_
271 << " should_send_stop_waiting: " << should_send_stop_waiting_
272 << " number of queued_control_frames: "
273 << queued_control_frames_.size();
274 if (!queued_control_frames_.empty()) {
275 QUIC_LOG(INFO) << queued_control_frames_[0];
276 }
277 delegate_->OnUnrecoverableError(QUIC_FAILED_TO_SERIALIZE_PACKET,
278 "Single frame cannot fit into a packet",
279 ConnectionCloseSource::FROM_SELF);
280 return;
281 }
282 }
283 if (flush) {
284 packet_creator_.Flush();
285 }
286}
287
288bool QuicPacketGenerator::PacketFlusherAttached() const {
289 return flusher_attached_;
290}
291
292void QuicPacketGenerator::AttachPacketFlusher() {
293 flusher_attached_ = true;
294}
295
296void QuicPacketGenerator::Flush() {
297 SendQueuedFrames(/*flush=*/false);
298 packet_creator_.Flush();
299 SendRemainingPendingPadding();
300 flusher_attached_ = false;
301}
302
303void QuicPacketGenerator::FlushAllQueuedFrames() {
304 SendQueuedFrames(/*flush=*/true);
305}
306
307bool QuicPacketGenerator::HasQueuedFrames() const {
308 return packet_creator_.HasPendingFrames() || HasPendingFrames();
309}
310
311bool QuicPacketGenerator::IsPendingPacketEmpty() const {
312 return !packet_creator_.HasPendingFrames();
313}
314
315bool QuicPacketGenerator::HasPendingFrames() const {
316 return should_send_ack_ || should_send_stop_waiting_ ||
317 !queued_control_frames_.empty();
318}
319
320bool QuicPacketGenerator::AddNextPendingFrame() {
321 QUIC_BUG_IF(!flusher_attached_) << "Packet flusher is not attached when "
322 "generator tries to write control frames.";
323 if (should_send_ack_) {
324 should_send_ack_ = !packet_creator_.AddSavedFrame(
325 delegate_->GetUpdatedAckFrame(), next_transmission_type_);
326 return !should_send_ack_;
327 }
328
329 if (should_send_stop_waiting_) {
330 delegate_->PopulateStopWaitingFrame(&pending_stop_waiting_frame_);
331 // If we can't this add the frame now, then we still need to do so later.
332 should_send_stop_waiting_ = !packet_creator_.AddSavedFrame(
333 QuicFrame(pending_stop_waiting_frame_), next_transmission_type_);
334 // Return success if we have cleared out this flag (i.e., added the frame).
335 // If we still need to send, then the frame is full, and we have failed.
336 return !should_send_stop_waiting_;
337 }
338
339 QUIC_BUG_IF(queued_control_frames_.empty())
340 << "AddNextPendingFrame called with no queued control frames.";
341
342 if (!packet_creator_.AddSavedFrame(queued_control_frames_.back(),
343 next_transmission_type_)) {
344 // Packet was full.
345 return false;
346 }
347 queued_control_frames_.pop_back();
348 return true;
349}
350
351void QuicPacketGenerator::StopSendingVersion() {
352 packet_creator_.StopSendingVersion();
353}
354
355void QuicPacketGenerator::SetDiversificationNonce(
356 const DiversificationNonce& nonce) {
357 packet_creator_.SetDiversificationNonce(nonce);
358}
359
360QuicPacketNumber QuicPacketGenerator::packet_number() const {
361 return packet_creator_.packet_number();
362}
363
364QuicByteCount QuicPacketGenerator::GetCurrentMaxPacketLength() const {
365 return packet_creator_.max_packet_length();
366}
367
368void QuicPacketGenerator::SetMaxPacketLength(QuicByteCount length) {
369 DCHECK(packet_creator_.CanSetMaxPacketLength());
370 packet_creator_.SetMaxPacketLength(length);
371}
372
373std::unique_ptr<QuicEncryptedPacket>
374QuicPacketGenerator::SerializeVersionNegotiationPacket(
375 bool ietf_quic,
376 const ParsedQuicVersionVector& supported_versions) {
377 return packet_creator_.SerializeVersionNegotiationPacket(ietf_quic,
378 supported_versions);
379}
380
381OwningSerializedPacketPointer
382QuicPacketGenerator::SerializeConnectivityProbingPacket() {
383 return packet_creator_.SerializeConnectivityProbingPacket();
384}
385
386OwningSerializedPacketPointer
387QuicPacketGenerator::SerializePathChallengeConnectivityProbingPacket(
388 QuicPathFrameBuffer* payload) {
389 return packet_creator_.SerializePathChallengeConnectivityProbingPacket(
390 payload);
391}
392
393OwningSerializedPacketPointer
394QuicPacketGenerator::SerializePathResponseConnectivityProbingPacket(
395 const QuicDeque<QuicPathFrameBuffer>& payloads,
396 const bool is_padded) {
397 return packet_creator_.SerializePathResponseConnectivityProbingPacket(
398 payloads, is_padded);
399}
400
401void QuicPacketGenerator::ReserializeAllFrames(
402 const QuicPendingRetransmission& retransmission,
403 char* buffer,
404 size_t buffer_len) {
405 packet_creator_.ReserializeAllFrames(retransmission, buffer, buffer_len);
406}
407
408void QuicPacketGenerator::UpdatePacketNumberLength(
409 QuicPacketNumber least_packet_awaited_by_peer,
410 QuicPacketCount max_packets_in_flight) {
411 return packet_creator_.UpdatePacketNumberLength(least_packet_awaited_by_peer,
412 max_packets_in_flight);
413}
414
415void QuicPacketGenerator::SetConnectionIdLength(uint32_t length) {
416 if (length == 0) {
417 packet_creator_.SetConnectionIdIncluded(CONNECTION_ID_ABSENT);
418 } else {
419 packet_creator_.SetConnectionIdIncluded(CONNECTION_ID_PRESENT);
420 }
421}
422
423void QuicPacketGenerator::set_encryption_level(EncryptionLevel level) {
424 packet_creator_.set_encryption_level(level);
425}
426
427void QuicPacketGenerator::SetEncrypter(
428 EncryptionLevel level,
429 std::unique_ptr<QuicEncrypter> encrypter) {
430 packet_creator_.SetEncrypter(level, std::move(encrypter));
431}
432
433void QuicPacketGenerator::AddRandomPadding() {
434 packet_creator_.AddPendingPadding(
435 random_generator_->RandUint64() % kMaxNumRandomPaddingBytes + 1);
436}
437
438void QuicPacketGenerator::SendRemainingPendingPadding() {
439 while (packet_creator_.pending_padding_bytes() > 0 && !HasQueuedFrames() &&
440 CanSendWithNextPendingFrameAddition()) {
441 packet_creator_.Flush();
442 }
443}
444
445bool QuicPacketGenerator::HasRetransmittableFrames() const {
446 return !queued_control_frames_.empty() ||
447 packet_creator_.HasPendingRetransmittableFrames();
448}
449
450bool QuicPacketGenerator::HasPendingStreamFramesOfStream(
451 QuicStreamId id) const {
452 return packet_creator_.HasPendingStreamFramesOfStream(id);
453}
454
455void QuicPacketGenerator::SetTransmissionType(TransmissionType type) {
456 packet_creator_.SetTransmissionType(type);
457 if (packet_creator_.ShouldSetTransmissionTypeForNextFrame()) {
458 next_transmission_type_ = type;
459 }
460}
461
462void QuicPacketGenerator::SetCanSetTransmissionType(
463 bool can_set_transmission_type) {
464 packet_creator_.set_can_set_transmission_type(can_set_transmission_type);
465}
466
467MessageStatus QuicPacketGenerator::AddMessageFrame(QuicMessageId message_id,
468 QuicMemSliceSpan message) {
469 QUIC_BUG_IF(!flusher_attached_) << "Packet flusher is not attached when "
470 "generator tries to add message frame.";
471 if (deprecate_ack_bundling_mode_) {
472 MaybeBundleAckOpportunistically();
473 }
474 const QuicByteCount message_length = message.total_length();
475 if (message_length > GetLargestMessagePayload()) {
476 return MESSAGE_STATUS_TOO_LARGE;
477 }
478 SendQueuedFrames(/*flush=*/false);
479 if (!packet_creator_.HasRoomForMessageFrame(message_length)) {
480 packet_creator_.Flush();
481 }
wub553a9662019-03-28 20:13:23 -0700482 QuicMessageFrame* frame = new QuicMessageFrame(message_id, message);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500483 const bool success =
484 packet_creator_.AddSavedFrame(QuicFrame(frame), next_transmission_type_);
485 if (!success) {
486 QUIC_BUG << "Failed to send message " << message_id;
487 delete frame;
488 return MESSAGE_STATUS_INTERNAL_ERROR;
489 }
490 return MESSAGE_STATUS_SUCCESS;
491}
492
493void QuicPacketGenerator::MaybeBundleAckOpportunistically() {
494 DCHECK(deprecate_ack_bundling_mode_);
495 if (packet_creator_.has_ack()) {
496 // Ack already queued, nothing to do.
497 return;
498 }
499 if (!delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
500 NOT_HANDSHAKE)) {
501 return;
502 }
503 const bool flushed =
504 FlushAckFrame(delegate_->MaybeBundleAckOpportunistically());
505 DCHECK(flushed);
506}
507
508bool QuicPacketGenerator::FlushAckFrame(const QuicFrames& frames) {
509 QUIC_BUG_IF(!flusher_attached_) << "Packet flusher is not attached when "
510 "generator tries to send ACK frame.";
511 for (const auto& frame : frames) {
512 DCHECK(frame.type == ACK_FRAME || frame.type == STOP_WAITING_FRAME);
513 if (packet_creator_.HasPendingFrames()) {
514 if (packet_creator_.AddSavedFrame(frame, next_transmission_type_)) {
515 // There is pending frames and current frame fits.
516 continue;
517 }
518 }
519 DCHECK(!packet_creator_.HasPendingFrames());
520 // There is no pending frames, consult the delegate whether a packet can be
521 // generated.
522 if (!delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
523 NOT_HANDSHAKE)) {
524 return false;
525 }
526 const bool success =
527 packet_creator_.AddSavedFrame(frame, next_transmission_type_);
528 QUIC_BUG_IF(!success) << "Failed to flush " << frame;
529 }
530 return true;
531}
532
533QuicPacketLength QuicPacketGenerator::GetLargestMessagePayload() const {
534 return packet_creator_.GetLargestMessagePayload();
535}
536
QUICHE teamc65d1d12019-03-19 20:58:04 -0700537void QuicPacketGenerator::SetConnectionId(QuicConnectionId connection_id) {
538 packet_creator_.SetConnectionId(connection_id);
539}
540
QUICHE teama6ef0a62019-03-07 20:34:33 -0500541} // namespace quic