• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "quiche/quic/core/quic_packet_creator.h"
6 
7 #include <algorithm>
8 #include <cstddef>
9 #include <cstdint>
10 #include <limits>
11 #include <string>
12 #include <utility>
13 
14 #include "absl/base/macros.h"
15 #include "absl/base/optimization.h"
16 #include "absl/strings/str_cat.h"
17 #include "absl/strings/str_join.h"
18 #include "absl/strings/string_view.h"
19 #include "absl/types/optional.h"
20 #include "quiche/quic/core/crypto/crypto_protocol.h"
21 #include "quiche/quic/core/frames/quic_frame.h"
22 #include "quiche/quic/core/frames/quic_padding_frame.h"
23 #include "quiche/quic/core/frames/quic_path_challenge_frame.h"
24 #include "quiche/quic/core/frames/quic_stream_frame.h"
25 #include "quiche/quic/core/quic_chaos_protector.h"
26 #include "quiche/quic/core/quic_connection_id.h"
27 #include "quiche/quic/core/quic_constants.h"
28 #include "quiche/quic/core/quic_data_writer.h"
29 #include "quiche/quic/core/quic_error_codes.h"
30 #include "quiche/quic/core/quic_types.h"
31 #include "quiche/quic/core/quic_utils.h"
32 #include "quiche/quic/core/quic_versions.h"
33 #include "quiche/quic/platform/api/quic_bug_tracker.h"
34 #include "quiche/quic/platform/api/quic_exported_stats.h"
35 #include "quiche/quic/platform/api/quic_flag_utils.h"
36 #include "quiche/quic/platform/api/quic_flags.h"
37 #include "quiche/quic/platform/api/quic_logging.h"
38 #include "quiche/quic/platform/api/quic_server_stats.h"
39 #include "quiche/common/print_elements.h"
40 
41 namespace quic {
42 namespace {
43 
EncryptionlevelToLongHeaderType(EncryptionLevel level)44 QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
45   switch (level) {
46     case ENCRYPTION_INITIAL:
47       return INITIAL;
48     case ENCRYPTION_HANDSHAKE:
49       return HANDSHAKE;
50     case ENCRYPTION_ZERO_RTT:
51       return ZERO_RTT_PROTECTED;
52     case ENCRYPTION_FORWARD_SECURE:
53       QUIC_BUG(quic_bug_12398_1)
54           << "Try to derive long header type for packet with encryption level: "
55           << level;
56       return INVALID_PACKET_TYPE;
57     default:
58       QUIC_BUG(quic_bug_10752_1) << level;
59       return INVALID_PACKET_TYPE;
60   }
61 }
62 
LogCoalesceStreamFrameStatus(bool success)63 void LogCoalesceStreamFrameStatus(bool success) {
64   QUIC_HISTOGRAM_BOOL("QuicSession.CoalesceStreamFrameStatus", success,
65                       "Success rate of coalesing stream frames attempt.");
66 }
67 
68 // ScopedPacketContextSwitcher saves |packet|'s states and change states
69 // during its construction. When the switcher goes out of scope, it restores
70 // saved states.
71 class ScopedPacketContextSwitcher {
72  public:
ScopedPacketContextSwitcher(QuicPacketNumber packet_number,QuicPacketNumberLength packet_number_length,EncryptionLevel encryption_level,SerializedPacket * packet)73   ScopedPacketContextSwitcher(QuicPacketNumber packet_number,
74                               QuicPacketNumberLength packet_number_length,
75                               EncryptionLevel encryption_level,
76                               SerializedPacket* packet)
77 
78       : saved_packet_number_(packet->packet_number),
79         saved_packet_number_length_(packet->packet_number_length),
80         saved_encryption_level_(packet->encryption_level),
81         packet_(packet) {
82     packet_->packet_number = packet_number,
83     packet_->packet_number_length = packet_number_length;
84     packet_->encryption_level = encryption_level;
85   }
86 
~ScopedPacketContextSwitcher()87   ~ScopedPacketContextSwitcher() {
88     packet_->packet_number = saved_packet_number_;
89     packet_->packet_number_length = saved_packet_number_length_;
90     packet_->encryption_level = saved_encryption_level_;
91   }
92 
93  private:
94   const QuicPacketNumber saved_packet_number_;
95   const QuicPacketNumberLength saved_packet_number_length_;
96   const EncryptionLevel saved_encryption_level_;
97   SerializedPacket* packet_;
98 };
99 
100 }  // namespace
101 
102 #define ENDPOINT \
103   (framer_->perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ")
104 
QuicPacketCreator(QuicConnectionId server_connection_id,QuicFramer * framer,DelegateInterface * delegate)105 QuicPacketCreator::QuicPacketCreator(QuicConnectionId server_connection_id,
106                                      QuicFramer* framer,
107                                      DelegateInterface* delegate)
108     : QuicPacketCreator(server_connection_id, framer, QuicRandom::GetInstance(),
109                         delegate) {}
110 
QuicPacketCreator(QuicConnectionId server_connection_id,QuicFramer * framer,QuicRandom * random,DelegateInterface * delegate)111 QuicPacketCreator::QuicPacketCreator(QuicConnectionId server_connection_id,
112                                      QuicFramer* framer, QuicRandom* random,
113                                      DelegateInterface* delegate)
114     : delegate_(delegate),
115       debug_delegate_(nullptr),
116       framer_(framer),
117       random_(random),
118       send_version_in_packet_(framer->perspective() == Perspective::IS_CLIENT),
119       have_diversification_nonce_(false),
120       max_packet_length_(0),
121       server_connection_id_included_(CONNECTION_ID_PRESENT),
122       packet_size_(0),
123       server_connection_id_(server_connection_id),
124       client_connection_id_(EmptyQuicConnectionId()),
125       packet_(QuicPacketNumber(), PACKET_1BYTE_PACKET_NUMBER, nullptr, 0, false,
126               false),
127       pending_padding_bytes_(0),
128       needs_full_padding_(false),
129       next_transmission_type_(NOT_RETRANSMISSION),
130       flusher_attached_(false),
131       fully_pad_crypto_handshake_packets_(true),
132       latched_hard_max_packet_length_(0),
133       max_datagram_frame_size_(0) {
134   SetMaxPacketLength(kDefaultMaxPacketSize);
135   if (!framer_->version().UsesTls()) {
136     // QUIC+TLS negotiates the maximum datagram frame size via the
137     // IETF QUIC max_datagram_frame_size transport parameter.
138     // QUIC_CRYPTO however does not negotiate this so we set its value here.
139     SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize);
140   }
141 }
142 
~QuicPacketCreator()143 QuicPacketCreator::~QuicPacketCreator() {
144   DeleteFrames(&packet_.retransmittable_frames);
145 }
146 
SetEncrypter(EncryptionLevel level,std::unique_ptr<QuicEncrypter> encrypter)147 void QuicPacketCreator::SetEncrypter(EncryptionLevel level,
148                                      std::unique_ptr<QuicEncrypter> encrypter) {
149   framer_->SetEncrypter(level, std::move(encrypter));
150   max_plaintext_size_ = framer_->GetMaxPlaintextSize(max_packet_length_);
151 }
152 
CanSetMaxPacketLength() const153 bool QuicPacketCreator::CanSetMaxPacketLength() const {
154   // |max_packet_length_| should not be changed mid-packet.
155   return queued_frames_.empty();
156 }
157 
SetMaxPacketLength(QuicByteCount length)158 void QuicPacketCreator::SetMaxPacketLength(QuicByteCount length) {
159   QUICHE_DCHECK(CanSetMaxPacketLength()) << ENDPOINT;
160 
161   // Avoid recomputing |max_plaintext_size_| if the length does not actually
162   // change.
163   if (length == max_packet_length_) {
164     return;
165   }
166   QUIC_DVLOG(1) << ENDPOINT << "Updating packet creator max packet length from "
167                 << max_packet_length_ << " to " << length;
168 
169   max_packet_length_ = length;
170   max_plaintext_size_ = framer_->GetMaxPlaintextSize(max_packet_length_);
171   QUIC_BUG_IF(
172       quic_bug_12398_2,
173       max_plaintext_size_ - PacketHeaderSize() <
174           MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength()))
175       << ENDPOINT << "Attempted to set max packet length too small";
176 }
177 
SetMaxDatagramFrameSize(QuicByteCount max_datagram_frame_size)178 void QuicPacketCreator::SetMaxDatagramFrameSize(
179     QuicByteCount max_datagram_frame_size) {
180   constexpr QuicByteCount upper_bound =
181       std::min<QuicByteCount>(std::numeric_limits<QuicPacketLength>::max(),
182                               std::numeric_limits<size_t>::max());
183   if (max_datagram_frame_size > upper_bound) {
184     // A value of |max_datagram_frame_size| that is equal or greater than
185     // 2^16-1 is effectively infinite because QUIC packets cannot be that large.
186     // We therefore clamp the value here to allow us to safely cast
187     // |max_datagram_frame_size_| to QuicPacketLength or size_t.
188     max_datagram_frame_size = upper_bound;
189   }
190   max_datagram_frame_size_ = max_datagram_frame_size;
191 }
192 
SetSoftMaxPacketLength(QuicByteCount length)193 void QuicPacketCreator::SetSoftMaxPacketLength(QuicByteCount length) {
194   QUICHE_DCHECK(CanSetMaxPacketLength()) << ENDPOINT;
195   if (length > max_packet_length_) {
196     QUIC_BUG(quic_bug_10752_2)
197         << ENDPOINT
198         << "Try to increase max_packet_length_ in "
199            "SetSoftMaxPacketLength, use SetMaxPacketLength instead.";
200     return;
201   }
202   if (framer_->GetMaxPlaintextSize(length) <
203       PacketHeaderSize() +
204           MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength())) {
205     // Please note: this would not guarantee to fit next packet if the size of
206     // packet header increases (e.g., encryption level changes).
207     QUIC_DLOG(INFO) << ENDPOINT << length
208                     << " is too small to fit packet header";
209     RemoveSoftMaxPacketLength();
210     return;
211   }
212   QUIC_DVLOG(1) << ENDPOINT << "Setting soft max packet length to: " << length;
213   latched_hard_max_packet_length_ = max_packet_length_;
214   max_packet_length_ = length;
215   max_plaintext_size_ = framer_->GetMaxPlaintextSize(length);
216 }
217 
218 // Stops serializing version of the protocol in packets sent after this call.
219 // A packet that is already open might send kQuicVersionSize bytes less than the
220 // maximum packet size if we stop sending version before it is serialized.
StopSendingVersion()221 void QuicPacketCreator::StopSendingVersion() {
222   QUICHE_DCHECK(send_version_in_packet_) << ENDPOINT;
223   QUICHE_DCHECK(!version().HasIetfInvariantHeader()) << ENDPOINT;
224   send_version_in_packet_ = false;
225   if (packet_size_ > 0) {
226     QUICHE_DCHECK_LT(kQuicVersionSize, packet_size_) << ENDPOINT;
227     packet_size_ -= kQuicVersionSize;
228   }
229 }
230 
SetDiversificationNonce(const DiversificationNonce & nonce)231 void QuicPacketCreator::SetDiversificationNonce(
232     const DiversificationNonce& nonce) {
233   QUICHE_DCHECK(!have_diversification_nonce_) << ENDPOINT;
234   have_diversification_nonce_ = true;
235   diversification_nonce_ = nonce;
236 }
237 
UpdatePacketNumberLength(QuicPacketNumber least_packet_awaited_by_peer,QuicPacketCount max_packets_in_flight)238 void QuicPacketCreator::UpdatePacketNumberLength(
239     QuicPacketNumber least_packet_awaited_by_peer,
240     QuicPacketCount max_packets_in_flight) {
241   if (!queued_frames_.empty()) {
242     // Don't change creator state if there are frames queued.
243     QUIC_BUG(quic_bug_10752_3)
244         << ENDPOINT << "Called UpdatePacketNumberLength with "
245         << queued_frames_.size()
246         << " queued_frames.  First frame type:" << queued_frames_.front().type
247         << " last frame type:" << queued_frames_.back().type;
248     return;
249   }
250 
251   const QuicPacketNumber next_packet_number = NextSendingPacketNumber();
252   QUICHE_DCHECK_LE(least_packet_awaited_by_peer, next_packet_number)
253       << ENDPOINT;
254   const uint64_t current_delta =
255       next_packet_number - least_packet_awaited_by_peer;
256   const uint64_t delta = std::max(current_delta, max_packets_in_flight);
257   const QuicPacketNumberLength packet_number_length =
258       QuicFramer::GetMinPacketNumberLength(QuicPacketNumber(delta * 4));
259   if (packet_.packet_number_length == packet_number_length) {
260     return;
261   }
262   QUIC_DVLOG(1) << ENDPOINT << "Updating packet number length from "
263                 << static_cast<int>(packet_.packet_number_length) << " to "
264                 << static_cast<int>(packet_number_length)
265                 << ", least_packet_awaited_by_peer: "
266                 << least_packet_awaited_by_peer
267                 << " max_packets_in_flight: " << max_packets_in_flight
268                 << " next_packet_number: " << next_packet_number;
269   packet_.packet_number_length = packet_number_length;
270 }
271 
SkipNPacketNumbers(QuicPacketCount count,QuicPacketNumber least_packet_awaited_by_peer,QuicPacketCount max_packets_in_flight)272 void QuicPacketCreator::SkipNPacketNumbers(
273     QuicPacketCount count, QuicPacketNumber least_packet_awaited_by_peer,
274     QuicPacketCount max_packets_in_flight) {
275   if (!queued_frames_.empty()) {
276     // Don't change creator state if there are frames queued.
277     QUIC_BUG(quic_bug_10752_4)
278         << ENDPOINT << "Called SkipNPacketNumbers with "
279         << queued_frames_.size()
280         << " queued_frames.  First frame type:" << queued_frames_.front().type
281         << " last frame type:" << queued_frames_.back().type;
282     return;
283   }
284   if (packet_.packet_number > packet_.packet_number + count) {
285     // Skipping count packet numbers causes packet number wrapping around,
286     // reject it.
287     QUIC_LOG(WARNING) << ENDPOINT << "Skipping " << count
288                       << " packet numbers causes packet number wrapping "
289                          "around, least_packet_awaited_by_peer: "
290                       << least_packet_awaited_by_peer
291                       << " packet_number:" << packet_.packet_number;
292     return;
293   }
294   packet_.packet_number += count;
295   // Packet number changes, update packet number length if necessary.
296   UpdatePacketNumberLength(least_packet_awaited_by_peer, max_packets_in_flight);
297 }
298 
ConsumeCryptoDataToFillCurrentPacket(EncryptionLevel level,size_t write_length,QuicStreamOffset offset,bool needs_full_padding,TransmissionType transmission_type,QuicFrame * frame)299 bool QuicPacketCreator::ConsumeCryptoDataToFillCurrentPacket(
300     EncryptionLevel level, size_t write_length, QuicStreamOffset offset,
301     bool needs_full_padding, TransmissionType transmission_type,
302     QuicFrame* frame) {
303   QUIC_DVLOG(2) << ENDPOINT << "ConsumeCryptoDataToFillCurrentPacket " << level
304                 << " write_length " << write_length << " offset " << offset
305                 << (needs_full_padding ? " needs_full_padding" : "") << " "
306                 << transmission_type;
307   if (!CreateCryptoFrame(level, write_length, offset, frame)) {
308     return false;
309   }
310   // When crypto data was sent in stream frames, ConsumeData is called with
311   // |needs_full_padding = true|. Keep the same behavior here when sending
312   // crypto frames.
313   //
314   // TODO(nharper): Check what the IETF drafts say about padding out initial
315   // messages and change this as appropriate.
316   if (needs_full_padding) {
317     needs_full_padding_ = true;
318   }
319   return AddFrame(*frame, transmission_type);
320 }
321 
ConsumeDataToFillCurrentPacket(QuicStreamId id,size_t data_size,QuicStreamOffset offset,bool fin,bool needs_full_padding,TransmissionType transmission_type,QuicFrame * frame)322 bool QuicPacketCreator::ConsumeDataToFillCurrentPacket(
323     QuicStreamId id, size_t data_size, QuicStreamOffset offset, bool fin,
324     bool needs_full_padding, TransmissionType transmission_type,
325     QuicFrame* frame) {
326   if (!HasRoomForStreamFrame(id, offset, data_size)) {
327     return false;
328   }
329   CreateStreamFrame(id, data_size, offset, fin, frame);
330   // Explicitly disallow multi-packet CHLOs.
331   if (GetQuicFlag(quic_enforce_single_packet_chlo) &&
332       StreamFrameIsClientHello(frame->stream_frame) &&
333       frame->stream_frame.data_length < data_size) {
334     const std::string error_details =
335         "Client hello won't fit in a single packet.";
336     QUIC_BUG(quic_bug_10752_5)
337         << ENDPOINT << error_details << " Constructed stream frame length: "
338         << frame->stream_frame.data_length << " CHLO length: " << data_size;
339     delegate_->OnUnrecoverableError(QUIC_CRYPTO_CHLO_TOO_LARGE, error_details);
340     return false;
341   }
342   if (!AddFrame(*frame, transmission_type)) {
343     // Fails if we try to write unencrypted stream data.
344     return false;
345   }
346   if (needs_full_padding) {
347     needs_full_padding_ = true;
348   }
349 
350   return true;
351 }
352 
HasRoomForStreamFrame(QuicStreamId id,QuicStreamOffset offset,size_t data_size)353 bool QuicPacketCreator::HasRoomForStreamFrame(QuicStreamId id,
354                                               QuicStreamOffset offset,
355                                               size_t data_size) {
356   const size_t min_stream_frame_size = QuicFramer::GetMinStreamFrameSize(
357       framer_->transport_version(), id, offset, /*last_frame_in_packet=*/true,
358       data_size);
359   if (BytesFree() > min_stream_frame_size) {
360     return true;
361   }
362   if (!RemoveSoftMaxPacketLength()) {
363     return false;
364   }
365   return BytesFree() > min_stream_frame_size;
366 }
367 
HasRoomForMessageFrame(QuicByteCount length)368 bool QuicPacketCreator::HasRoomForMessageFrame(QuicByteCount length) {
369   const size_t message_frame_size = QuicFramer::GetMessageFrameSize(
370       framer_->transport_version(), /*last_frame_in_packet=*/true, length);
371   if (static_cast<QuicByteCount>(message_frame_size) >
372       max_datagram_frame_size_) {
373     return false;
374   }
375   if (BytesFree() >= message_frame_size) {
376     return true;
377   }
378   if (!RemoveSoftMaxPacketLength()) {
379     return false;
380   }
381   return BytesFree() >= message_frame_size;
382 }
383 
384 // static
StreamFramePacketOverhead(QuicTransportVersion version,uint8_t destination_connection_id_length,uint8_t source_connection_id_length,bool include_version,bool include_diversification_nonce,QuicPacketNumberLength packet_number_length,quiche::QuicheVariableLengthIntegerLength retry_token_length_length,quiche::QuicheVariableLengthIntegerLength length_length,QuicStreamOffset offset)385 size_t QuicPacketCreator::StreamFramePacketOverhead(
386     QuicTransportVersion version, uint8_t destination_connection_id_length,
387     uint8_t source_connection_id_length, bool include_version,
388     bool include_diversification_nonce,
389     QuicPacketNumberLength packet_number_length,
390     quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
391     quiche::QuicheVariableLengthIntegerLength length_length,
392     QuicStreamOffset offset) {
393   return GetPacketHeaderSize(version, destination_connection_id_length,
394                              source_connection_id_length, include_version,
395                              include_diversification_nonce,
396                              packet_number_length, retry_token_length_length, 0,
397                              length_length) +
398 
399          // Assumes a packet with a single stream frame, which omits the length,
400          // causing the data length argument to be ignored.
401          QuicFramer::GetMinStreamFrameSize(version, 1u, offset, true,
402                                            kMaxOutgoingPacketSize /* unused */);
403 }
404 
CreateStreamFrame(QuicStreamId id,size_t data_size,QuicStreamOffset offset,bool fin,QuicFrame * frame)405 void QuicPacketCreator::CreateStreamFrame(QuicStreamId id, size_t data_size,
406                                           QuicStreamOffset offset, bool fin,
407                                           QuicFrame* frame) {
408   // Make sure max_packet_length_ is greater than the largest possible overhead
409   // or max_packet_length_ is set to the soft limit.
410   QUICHE_DCHECK(
411       max_packet_length_ >
412           StreamFramePacketOverhead(
413               framer_->transport_version(), GetDestinationConnectionIdLength(),
414               GetSourceConnectionIdLength(), kIncludeVersion,
415               IncludeNonceInPublicHeader(), PACKET_6BYTE_PACKET_NUMBER,
416               GetRetryTokenLengthLength(), GetLengthLength(), offset) ||
417       latched_hard_max_packet_length_ > 0)
418       << ENDPOINT;
419 
420   QUIC_BUG_IF(quic_bug_12398_3, !HasRoomForStreamFrame(id, offset, data_size))
421       << ENDPOINT << "No room for Stream frame, BytesFree: " << BytesFree()
422       << " MinStreamFrameSize: "
423       << QuicFramer::GetMinStreamFrameSize(framer_->transport_version(), id,
424                                            offset, true, data_size);
425 
426   QUIC_BUG_IF(quic_bug_12398_4, data_size == 0 && !fin)
427       << ENDPOINT << "Creating a stream frame for stream ID:" << id
428       << " with no data or fin.";
429   size_t min_frame_size = QuicFramer::GetMinStreamFrameSize(
430       framer_->transport_version(), id, offset,
431       /* last_frame_in_packet= */ true, data_size);
432   size_t bytes_consumed =
433       std::min<size_t>(BytesFree() - min_frame_size, data_size);
434 
435   bool set_fin = fin && bytes_consumed == data_size;  // Last frame.
436   *frame = QuicFrame(QuicStreamFrame(id, set_fin, offset, bytes_consumed));
437 }
438 
CreateCryptoFrame(EncryptionLevel level,size_t write_length,QuicStreamOffset offset,QuicFrame * frame)439 bool QuicPacketCreator::CreateCryptoFrame(EncryptionLevel level,
440                                           size_t write_length,
441                                           QuicStreamOffset offset,
442                                           QuicFrame* frame) {
443   const size_t min_frame_size =
444       QuicFramer::GetMinCryptoFrameSize(write_length, offset);
445   if (BytesFree() <= min_frame_size &&
446       (!RemoveSoftMaxPacketLength() || BytesFree() <= min_frame_size)) {
447     return false;
448   }
449   size_t max_write_length = BytesFree() - min_frame_size;
450   size_t bytes_consumed = std::min<size_t>(max_write_length, write_length);
451   *frame = QuicFrame(new QuicCryptoFrame(level, offset, bytes_consumed));
452   return true;
453 }
454 
FlushCurrentPacket()455 void QuicPacketCreator::FlushCurrentPacket() {
456   if (!HasPendingFrames() && pending_padding_bytes_ == 0) {
457     return;
458   }
459 
460   ABSL_CACHELINE_ALIGNED char stack_buffer[kMaxOutgoingPacketSize];
461   QuicOwnedPacketBuffer external_buffer(delegate_->GetPacketBuffer());
462 
463   if (external_buffer.buffer == nullptr) {
464     external_buffer.buffer = stack_buffer;
465     external_buffer.release_buffer = nullptr;
466   }
467 
468   QUICHE_DCHECK_EQ(nullptr, packet_.encrypted_buffer) << ENDPOINT;
469   if (!SerializePacket(std::move(external_buffer), kMaxOutgoingPacketSize,
470                        /*allow_padding=*/true)) {
471     return;
472   }
473   OnSerializedPacket();
474 }
475 
OnSerializedPacket()476 void QuicPacketCreator::OnSerializedPacket() {
477   QUIC_BUG_IF(quic_bug_12398_5, packet_.encrypted_buffer == nullptr)
478       << ENDPOINT;
479 
480   // Clear bytes_not_retransmitted for packets containing only
481   // NOT_RETRANSMISSION frames.
482   if (packet_.transmission_type == NOT_RETRANSMISSION) {
483     packet_.bytes_not_retransmitted.reset();
484   }
485 
486   SerializedPacket packet(std::move(packet_));
487   ClearPacket();
488   RemoveSoftMaxPacketLength();
489   delegate_->OnSerializedPacket(std::move(packet));
490 }
491 
ClearPacket()492 void QuicPacketCreator::ClearPacket() {
493   packet_.has_ack = false;
494   packet_.has_stop_waiting = false;
495   packet_.has_ack_ecn = false;
496   packet_.has_crypto_handshake = NOT_HANDSHAKE;
497   packet_.transmission_type = NOT_RETRANSMISSION;
498   packet_.encrypted_buffer = nullptr;
499   packet_.encrypted_length = 0;
500   packet_.has_ack_frequency = false;
501   packet_.has_message = false;
502   packet_.fate = SEND_TO_WRITER;
503   QUIC_BUG_IF(quic_bug_12398_6, packet_.release_encrypted_buffer != nullptr)
504       << ENDPOINT << "packet_.release_encrypted_buffer should be empty";
505   packet_.release_encrypted_buffer = nullptr;
506   QUICHE_DCHECK(packet_.retransmittable_frames.empty()) << ENDPOINT;
507   QUICHE_DCHECK(packet_.nonretransmittable_frames.empty()) << ENDPOINT;
508   packet_.largest_acked.Clear();
509   needs_full_padding_ = false;
510   packet_.bytes_not_retransmitted.reset();
511   packet_.initial_header.reset();
512 }
513 
ReserializeInitialPacketInCoalescedPacket(const SerializedPacket & packet,size_t padding_size,char * buffer,size_t buffer_len)514 size_t QuicPacketCreator::ReserializeInitialPacketInCoalescedPacket(
515     const SerializedPacket& packet, size_t padding_size, char* buffer,
516     size_t buffer_len) {
517   QUIC_BUG_IF(quic_bug_12398_7, packet.encryption_level != ENCRYPTION_INITIAL);
518   QUIC_BUG_IF(quic_bug_12398_8, packet.nonretransmittable_frames.empty() &&
519                                     packet.retransmittable_frames.empty())
520       << ENDPOINT
521       << "Attempt to serialize empty ENCRYPTION_INITIAL packet in coalesced "
522          "packet";
523 
524   if (HasPendingFrames()) {
525     QUIC_BUG(quic_packet_creator_unexpected_queued_frames)
526         << "Unexpected queued frames: " << GetPendingFramesInfo();
527     return 0;
528   }
529 
530   ScopedPacketContextSwitcher switcher(
531       packet.packet_number -
532           1,  // -1 because serialize packet increase packet number.
533       packet.packet_number_length, packet.encryption_level, &packet_);
534   for (const QuicFrame& frame : packet.nonretransmittable_frames) {
535     if (!AddFrame(frame, packet.transmission_type)) {
536       QUIC_BUG(quic_bug_10752_6)
537           << ENDPOINT << "Failed to serialize frame: " << frame;
538       return 0;
539     }
540   }
541   for (const QuicFrame& frame : packet.retransmittable_frames) {
542     if (!AddFrame(frame, packet.transmission_type)) {
543       QUIC_BUG(quic_bug_10752_7)
544           << ENDPOINT << "Failed to serialize frame: " << frame;
545       return 0;
546     }
547   }
548   // Add necessary padding.
549   if (padding_size > 0) {
550     QUIC_DVLOG(2) << ENDPOINT << "Add padding of size: " << padding_size;
551     if (!AddFrame(QuicFrame(QuicPaddingFrame(padding_size)),
552                   packet.transmission_type)) {
553       QUIC_BUG(quic_bug_10752_8)
554           << ENDPOINT << "Failed to add padding of size " << padding_size
555           << " when serializing ENCRYPTION_INITIAL "
556              "packet in coalesced packet";
557       return 0;
558     }
559   }
560 
561   if (!SerializePacket(QuicOwnedPacketBuffer(buffer, nullptr), buffer_len,
562                        /*allow_padding=*/false)) {
563     return 0;
564   }
565   if (!packet.initial_header.has_value() ||
566       !packet_.initial_header.has_value()) {
567     QUIC_BUG(missing initial packet header)
568         << "initial serialized packet does not have header populated";
569   } else if (packet.initial_header.value() != packet_.initial_header.value()) {
570     QUIC_BUG(initial packet header changed before reserialization)
571         << ENDPOINT << "original header: " << packet.initial_header.value()
572         << ", new header: " << packet_.initial_header.value();
573   }
574   const size_t encrypted_length = packet_.encrypted_length;
575   // Clear frames in packet_. No need to DeleteFrames since frames are owned by
576   // initial_packet.
577   packet_.retransmittable_frames.clear();
578   packet_.nonretransmittable_frames.clear();
579   ClearPacket();
580   return encrypted_length;
581 }
582 
CreateAndSerializeStreamFrame(QuicStreamId id,size_t write_length,QuicStreamOffset iov_offset,QuicStreamOffset stream_offset,bool fin,TransmissionType transmission_type,size_t * num_bytes_consumed)583 void QuicPacketCreator::CreateAndSerializeStreamFrame(
584     QuicStreamId id, size_t write_length, QuicStreamOffset iov_offset,
585     QuicStreamOffset stream_offset, bool fin,
586     TransmissionType transmission_type, size_t* num_bytes_consumed) {
587   // TODO(b/167222597): consider using ScopedSerializationFailureHandler.
588   QUICHE_DCHECK(queued_frames_.empty()) << ENDPOINT;
589   QUICHE_DCHECK(!QuicUtils::IsCryptoStreamId(transport_version(), id))
590       << ENDPOINT;
591   // Write out the packet header
592   QuicPacketHeader header;
593   FillPacketHeader(&header);
594   packet_.fate = delegate_->GetSerializedPacketFate(
595       /*is_mtu_discovery=*/false, packet_.encryption_level);
596   QUIC_DVLOG(1) << ENDPOINT << "fate of packet " << packet_.packet_number
597                 << ": " << SerializedPacketFateToString(packet_.fate) << " of "
598                 << EncryptionLevelToString(packet_.encryption_level);
599 
600   ABSL_CACHELINE_ALIGNED char stack_buffer[kMaxOutgoingPacketSize];
601   QuicOwnedPacketBuffer packet_buffer(delegate_->GetPacketBuffer());
602 
603   if (packet_buffer.buffer == nullptr) {
604     packet_buffer.buffer = stack_buffer;
605     packet_buffer.release_buffer = nullptr;
606   }
607 
608   char* encrypted_buffer = packet_buffer.buffer;
609 
610   QuicDataWriter writer(kMaxOutgoingPacketSize, encrypted_buffer);
611   size_t length_field_offset = 0;
612   if (!framer_->AppendPacketHeader(header, &writer, &length_field_offset)) {
613     QUIC_BUG(quic_bug_10752_9) << ENDPOINT << "AppendPacketHeader failed";
614     return;
615   }
616 
617   // Create a Stream frame with the remaining space.
618   QUIC_BUG_IF(quic_bug_12398_9, iov_offset == write_length && !fin)
619       << ENDPOINT << "Creating a stream frame with no data or fin.";
620   const size_t remaining_data_size = write_length - iov_offset;
621   size_t min_frame_size = QuicFramer::GetMinStreamFrameSize(
622       framer_->transport_version(), id, stream_offset,
623       /* last_frame_in_packet= */ true, remaining_data_size);
624   size_t available_size =
625       max_plaintext_size_ - writer.length() - min_frame_size;
626   size_t bytes_consumed = std::min<size_t>(available_size, remaining_data_size);
627   size_t plaintext_bytes_written = min_frame_size + bytes_consumed;
628   bool needs_padding = false;
629   const size_t min_plaintext_size =
630       MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength());
631   if (plaintext_bytes_written < min_plaintext_size) {
632     needs_padding = true;
633   }
634 
635   const bool set_fin = fin && (bytes_consumed == remaining_data_size);
636   QuicStreamFrame frame(id, set_fin, stream_offset, bytes_consumed);
637   if (debug_delegate_ != nullptr) {
638     debug_delegate_->OnFrameAddedToPacket(QuicFrame(frame));
639   }
640   QUIC_DVLOG(1) << ENDPOINT << "Adding frame: " << frame;
641 
642   QUIC_DVLOG(2) << ENDPOINT << "Serializing stream packet " << header << frame;
643 
644   // TODO(ianswett): AppendTypeByte and AppendStreamFrame could be optimized
645   // into one method that takes a QuicStreamFrame, if warranted.
646   if (needs_padding) {
647     if (!writer.WritePaddingBytes(min_plaintext_size -
648                                   plaintext_bytes_written)) {
649       QUIC_BUG(quic_bug_10752_12) << ENDPOINT << "Unable to add padding bytes";
650       return;
651     }
652     needs_padding = false;
653   }
654   bool omit_frame_length = !needs_padding;
655   if (!framer_->AppendTypeByte(QuicFrame(frame), omit_frame_length, &writer)) {
656     QUIC_BUG(quic_bug_10752_10) << ENDPOINT << "AppendTypeByte failed";
657     return;
658   }
659   if (!framer_->AppendStreamFrame(frame, omit_frame_length, &writer)) {
660     QUIC_BUG(quic_bug_10752_11) << ENDPOINT << "AppendStreamFrame failed";
661     return;
662   }
663   if (needs_padding && plaintext_bytes_written < min_plaintext_size &&
664       !writer.WritePaddingBytes(min_plaintext_size - plaintext_bytes_written)) {
665     QUIC_BUG(quic_bug_10752_12) << ENDPOINT << "Unable to add padding bytes";
666     return;
667   }
668 
669   if (!framer_->WriteIetfLongHeaderLength(header, &writer, length_field_offset,
670                                           packet_.encryption_level)) {
671     return;
672   }
673 
674   packet_.transmission_type = transmission_type;
675 
676   QUICHE_DCHECK(packet_.encryption_level == ENCRYPTION_FORWARD_SECURE ||
677                 packet_.encryption_level == ENCRYPTION_ZERO_RTT)
678       << ENDPOINT << packet_.encryption_level;
679   size_t encrypted_length = framer_->EncryptInPlace(
680       packet_.encryption_level, packet_.packet_number,
681       GetStartOfEncryptedData(framer_->transport_version(), header),
682       writer.length(), kMaxOutgoingPacketSize, encrypted_buffer);
683   if (encrypted_length == 0) {
684     QUIC_BUG(quic_bug_10752_13)
685         << ENDPOINT << "Failed to encrypt packet number "
686         << header.packet_number;
687     return;
688   }
689   // TODO(ianswett): Optimize the storage so RetransmitableFrames can be
690   // unioned with a QuicStreamFrame and a UniqueStreamBuffer.
691   *num_bytes_consumed = bytes_consumed;
692   packet_size_ = 0;
693   packet_.encrypted_buffer = encrypted_buffer;
694   packet_.encrypted_length = encrypted_length;
695 
696   packet_buffer.buffer = nullptr;
697   packet_.release_encrypted_buffer = std::move(packet_buffer).release_buffer;
698 
699   packet_.retransmittable_frames.push_back(QuicFrame(frame));
700   OnSerializedPacket();
701 }
702 
HasPendingFrames() const703 bool QuicPacketCreator::HasPendingFrames() const {
704   return !queued_frames_.empty();
705 }
706 
GetPendingFramesInfo() const707 std::string QuicPacketCreator::GetPendingFramesInfo() const {
708   return QuicFramesToString(queued_frames_);
709 }
710 
HasPendingRetransmittableFrames() const711 bool QuicPacketCreator::HasPendingRetransmittableFrames() const {
712   return !packet_.retransmittable_frames.empty();
713 }
714 
HasPendingStreamFramesOfStream(QuicStreamId id) const715 bool QuicPacketCreator::HasPendingStreamFramesOfStream(QuicStreamId id) const {
716   for (const auto& frame : packet_.retransmittable_frames) {
717     if (frame.type == STREAM_FRAME && frame.stream_frame.stream_id == id) {
718       return true;
719     }
720   }
721   return false;
722 }
723 
ExpansionOnNewFrame() const724 size_t QuicPacketCreator::ExpansionOnNewFrame() const {
725   // If the last frame in the packet is a message frame, then it will expand to
726   // include the varint message length when a new frame is added.
727   if (queued_frames_.empty()) {
728     return 0;
729   }
730   return ExpansionOnNewFrameWithLastFrame(queued_frames_.back(),
731                                           framer_->transport_version());
732 }
733 
734 // static
ExpansionOnNewFrameWithLastFrame(const QuicFrame & last_frame,QuicTransportVersion version)735 size_t QuicPacketCreator::ExpansionOnNewFrameWithLastFrame(
736     const QuicFrame& last_frame, QuicTransportVersion version) {
737   if (last_frame.type == MESSAGE_FRAME) {
738     return QuicDataWriter::GetVarInt62Len(
739         last_frame.message_frame->message_length);
740   }
741   if (last_frame.type != STREAM_FRAME) {
742     return 0;
743   }
744   if (VersionHasIetfQuicFrames(version)) {
745     return QuicDataWriter::GetVarInt62Len(last_frame.stream_frame.data_length);
746   }
747   return kQuicStreamPayloadLengthSize;
748 }
749 
BytesFree() const750 size_t QuicPacketCreator::BytesFree() const {
751   return max_plaintext_size_ -
752          std::min(max_plaintext_size_, PacketSize() + ExpansionOnNewFrame());
753 }
754 
BytesFreeForPadding() const755 size_t QuicPacketCreator::BytesFreeForPadding() const {
756   size_t consumed = PacketSize();
757   return max_plaintext_size_ - std::min(max_plaintext_size_, consumed);
758 }
759 
PacketSize() const760 size_t QuicPacketCreator::PacketSize() const {
761   return queued_frames_.empty() ? PacketHeaderSize() : packet_size_;
762 }
763 
AddPaddedSavedFrame(const QuicFrame & frame,TransmissionType transmission_type)764 bool QuicPacketCreator::AddPaddedSavedFrame(
765     const QuicFrame& frame, TransmissionType transmission_type) {
766   if (AddFrame(frame, transmission_type)) {
767     needs_full_padding_ = true;
768     return true;
769   }
770   return false;
771 }
772 
773 absl::optional<size_t>
MaybeBuildDataPacketWithChaosProtection(const QuicPacketHeader & header,char * buffer)774 QuicPacketCreator::MaybeBuildDataPacketWithChaosProtection(
775     const QuicPacketHeader& header, char* buffer) {
776   if (!GetQuicFlag(quic_enable_chaos_protection) ||
777       framer_->perspective() != Perspective::IS_CLIENT ||
778       packet_.encryption_level != ENCRYPTION_INITIAL ||
779       !framer_->version().UsesCryptoFrames() || queued_frames_.size() != 2u ||
780       queued_frames_[0].type != CRYPTO_FRAME ||
781       queued_frames_[1].type != PADDING_FRAME ||
782       // Do not perform chaos protection if we do not have a known number of
783       // padding bytes to work with.
784       queued_frames_[1].padding_frame.num_padding_bytes <= 0 ||
785       // Chaos protection relies on the framer using a crypto data producer,
786       // which is always the case in practice.
787       framer_->data_producer() == nullptr) {
788     return absl::nullopt;
789   }
790   const QuicCryptoFrame& crypto_frame = *queued_frames_[0].crypto_frame;
791   if (packet_.encryption_level != crypto_frame.level) {
792     QUIC_BUG(chaos frame level)
793         << ENDPOINT << packet_.encryption_level << " != " << crypto_frame.level;
794     return absl::nullopt;
795   }
796   QuicChaosProtector chaos_protector(
797       crypto_frame, queued_frames_[1].padding_frame.num_padding_bytes,
798       packet_size_, framer_, random_);
799   return chaos_protector.BuildDataPacket(header, buffer);
800 }
801 
SerializePacket(QuicOwnedPacketBuffer encrypted_buffer,size_t encrypted_buffer_len,bool allow_padding)802 bool QuicPacketCreator::SerializePacket(QuicOwnedPacketBuffer encrypted_buffer,
803                                         size_t encrypted_buffer_len,
804                                         bool allow_padding) {
805   if (packet_.encrypted_buffer != nullptr) {
806     const std::string error_details =
807         "Packet's encrypted buffer is not empty before serialization";
808     QUIC_BUG(quic_bug_10752_14) << ENDPOINT << error_details;
809     delegate_->OnUnrecoverableError(QUIC_FAILED_TO_SERIALIZE_PACKET,
810                                     error_details);
811     return false;
812   }
813   ScopedSerializationFailureHandler handler(this);
814 
815   QUICHE_DCHECK_LT(0u, encrypted_buffer_len) << ENDPOINT;
816   QUIC_BUG_IF(quic_bug_12398_10,
817               queued_frames_.empty() && pending_padding_bytes_ == 0)
818       << ENDPOINT << "Attempt to serialize empty packet";
819   QuicPacketHeader header;
820   // FillPacketHeader increments packet_number_.
821   FillPacketHeader(&header);
822   if (packet_.encryption_level == ENCRYPTION_INITIAL) {
823     packet_.initial_header = header;
824   }
825   if (delegate_ != nullptr) {
826     packet_.fate = delegate_->GetSerializedPacketFate(
827         /*is_mtu_discovery=*/QuicUtils::ContainsFrameType(queued_frames_,
828                                                           MTU_DISCOVERY_FRAME),
829         packet_.encryption_level);
830     QUIC_DVLOG(1) << ENDPOINT << "fate of packet " << packet_.packet_number
831                   << ": " << SerializedPacketFateToString(packet_.fate)
832                   << " of "
833                   << EncryptionLevelToString(packet_.encryption_level);
834   }
835 
836   if (allow_padding) {
837     MaybeAddPadding();
838   }
839 
840   QUIC_DVLOG(2) << ENDPOINT << "Serializing packet " << header
841                 << QuicFramesToString(queued_frames_) << " at encryption_level "
842                 << packet_.encryption_level
843                 << ", allow_padding:" << allow_padding;
844 
845   if (!framer_->HasEncrypterOfEncryptionLevel(packet_.encryption_level)) {
846     // TODO(fayang): Use QUIC_MISSING_WRITE_KEYS for serialization failures due
847     // to missing keys.
848     QUIC_BUG(quic_bug_10752_15)
849         << ENDPOINT << "Attempting to serialize " << header
850         << QuicFramesToString(queued_frames_) << " at missing encryption_level "
851         << packet_.encryption_level << " using " << framer_->version();
852     return false;
853   }
854 
855   QUICHE_DCHECK_GE(max_plaintext_size_, packet_size_) << ENDPOINT;
856   // Use the packet_size_ instead of the buffer size to ensure smaller
857   // packet sizes are properly used.
858 
859   size_t length;
860   absl::optional<size_t> length_with_chaos_protection =
861       MaybeBuildDataPacketWithChaosProtection(header, encrypted_buffer.buffer);
862   if (length_with_chaos_protection.has_value()) {
863     length = length_with_chaos_protection.value();
864   } else {
865     length = framer_->BuildDataPacket(header, queued_frames_,
866                                       encrypted_buffer.buffer, packet_size_,
867                                       packet_.encryption_level);
868   }
869 
870   if (length == 0) {
871     QUIC_BUG(quic_bug_10752_16)
872         << ENDPOINT << "Failed to serialize "
873         << QuicFramesToString(queued_frames_)
874         << " at encryption_level: " << packet_.encryption_level
875         << ", needs_full_padding_: " << needs_full_padding_
876         << ", pending_padding_bytes_: " << pending_padding_bytes_
877         << ", latched_hard_max_packet_length_: "
878         << latched_hard_max_packet_length_
879         << ", max_packet_length_: " << max_packet_length_
880         << ", header: " << header;
881     return false;
882   }
883 
884   // ACK Frames will be truncated due to length only if they're the only frame
885   // in the packet, and if packet_size_ was set to max_plaintext_size_. If
886   // truncation due to length occurred, then GetSerializedFrameLength will have
887   // returned all bytes free.
888   bool possibly_truncated_by_length = packet_size_ == max_plaintext_size_ &&
889                                       queued_frames_.size() == 1 &&
890                                       queued_frames_.back().type == ACK_FRAME;
891   // Because of possible truncation, we can't be confident that our
892   // packet size calculation worked correctly.
893   if (!possibly_truncated_by_length) {
894     QUICHE_DCHECK_EQ(packet_size_, length) << ENDPOINT;
895   }
896   const size_t encrypted_length = framer_->EncryptInPlace(
897       packet_.encryption_level, packet_.packet_number,
898       GetStartOfEncryptedData(framer_->transport_version(), header), length,
899       encrypted_buffer_len, encrypted_buffer.buffer);
900   if (encrypted_length == 0) {
901     QUIC_BUG(quic_bug_10752_17)
902         << ENDPOINT << "Failed to encrypt packet number "
903         << packet_.packet_number;
904     return false;
905   }
906 
907   packet_size_ = 0;
908   packet_.encrypted_buffer = encrypted_buffer.buffer;
909   packet_.encrypted_length = encrypted_length;
910 
911   encrypted_buffer.buffer = nullptr;
912   packet_.release_encrypted_buffer = std::move(encrypted_buffer).release_buffer;
913   return true;
914 }
915 
916 std::unique_ptr<SerializedPacket>
SerializeConnectivityProbingPacket()917 QuicPacketCreator::SerializeConnectivityProbingPacket() {
918   QUIC_BUG_IF(quic_bug_12398_11,
919               VersionHasIetfQuicFrames(framer_->transport_version()))
920       << ENDPOINT
921       << "Must not be version 99 to serialize padded ping connectivity probe";
922   RemoveSoftMaxPacketLength();
923   QuicPacketHeader header;
924   // FillPacketHeader increments packet_number_.
925   FillPacketHeader(&header);
926 
927   QUIC_DVLOG(2) << ENDPOINT << "Serializing connectivity probing packet "
928                 << header;
929 
930   std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]);
931   size_t length = BuildConnectivityProbingPacket(
932       header, buffer.get(), max_plaintext_size_, packet_.encryption_level);
933   QUICHE_DCHECK(length) << ENDPOINT;
934 
935   QUICHE_DCHECK_EQ(packet_.encryption_level, ENCRYPTION_FORWARD_SECURE)
936       << ENDPOINT;
937   const size_t encrypted_length = framer_->EncryptInPlace(
938       packet_.encryption_level, packet_.packet_number,
939       GetStartOfEncryptedData(framer_->transport_version(), header), length,
940       kMaxOutgoingPacketSize, buffer.get());
941   QUICHE_DCHECK(encrypted_length) << ENDPOINT;
942 
943   std::unique_ptr<SerializedPacket> serialize_packet(new SerializedPacket(
944       header.packet_number, header.packet_number_length, buffer.release(),
945       encrypted_length, /*has_ack=*/false, /*has_stop_waiting=*/false));
946 
947   serialize_packet->release_encrypted_buffer = [](const char* p) {
948     delete[] p;
949   };
950   serialize_packet->encryption_level = packet_.encryption_level;
951   serialize_packet->transmission_type = NOT_RETRANSMISSION;
952 
953   return serialize_packet;
954 }
955 
956 std::unique_ptr<SerializedPacket>
SerializePathChallengeConnectivityProbingPacket(const QuicPathFrameBuffer & payload)957 QuicPacketCreator::SerializePathChallengeConnectivityProbingPacket(
958     const QuicPathFrameBuffer& payload) {
959   QUIC_BUG_IF(quic_bug_12398_12,
960               !VersionHasIetfQuicFrames(framer_->transport_version()))
961       << ENDPOINT
962       << "Must be version 99 to serialize path challenge connectivity probe, "
963          "is version "
964       << framer_->transport_version();
965   RemoveSoftMaxPacketLength();
966   QuicPacketHeader header;
967   // FillPacketHeader increments packet_number_.
968   FillPacketHeader(&header);
969 
970   QUIC_DVLOG(2) << ENDPOINT << "Serializing path challenge packet " << header;
971 
972   std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]);
973   size_t length =
974       BuildPaddedPathChallengePacket(header, buffer.get(), max_plaintext_size_,
975                                      payload, packet_.encryption_level);
976   QUICHE_DCHECK(length) << ENDPOINT;
977 
978   QUICHE_DCHECK_EQ(packet_.encryption_level, ENCRYPTION_FORWARD_SECURE)
979       << ENDPOINT;
980   const size_t encrypted_length = framer_->EncryptInPlace(
981       packet_.encryption_level, packet_.packet_number,
982       GetStartOfEncryptedData(framer_->transport_version(), header), length,
983       kMaxOutgoingPacketSize, buffer.get());
984   QUICHE_DCHECK(encrypted_length) << ENDPOINT;
985 
986   std::unique_ptr<SerializedPacket> serialize_packet(
987       new SerializedPacket(header.packet_number, header.packet_number_length,
988                            buffer.release(), encrypted_length,
989                            /*has_ack=*/false, /*has_stop_waiting=*/false));
990 
991   serialize_packet->release_encrypted_buffer = [](const char* p) {
992     delete[] p;
993   };
994   serialize_packet->encryption_level = packet_.encryption_level;
995   serialize_packet->transmission_type = NOT_RETRANSMISSION;
996 
997   return serialize_packet;
998 }
999 
1000 std::unique_ptr<SerializedPacket>
SerializePathResponseConnectivityProbingPacket(const quiche::QuicheCircularDeque<QuicPathFrameBuffer> & payloads,const bool is_padded)1001 QuicPacketCreator::SerializePathResponseConnectivityProbingPacket(
1002     const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads,
1003     const bool is_padded) {
1004   QUIC_BUG_IF(quic_bug_12398_13,
1005               !VersionHasIetfQuicFrames(framer_->transport_version()))
1006       << ENDPOINT
1007       << "Must be version 99 to serialize path response connectivity probe, is "
1008          "version "
1009       << framer_->transport_version();
1010   RemoveSoftMaxPacketLength();
1011   QuicPacketHeader header;
1012   // FillPacketHeader increments packet_number_.
1013   FillPacketHeader(&header);
1014 
1015   QUIC_DVLOG(2) << ENDPOINT << "Serializing path response packet " << header;
1016 
1017   std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]);
1018   size_t length =
1019       BuildPathResponsePacket(header, buffer.get(), max_plaintext_size_,
1020                               payloads, is_padded, packet_.encryption_level);
1021   QUICHE_DCHECK(length) << ENDPOINT;
1022 
1023   QUICHE_DCHECK_EQ(packet_.encryption_level, ENCRYPTION_FORWARD_SECURE)
1024       << ENDPOINT;
1025   const size_t encrypted_length = framer_->EncryptInPlace(
1026       packet_.encryption_level, packet_.packet_number,
1027       GetStartOfEncryptedData(framer_->transport_version(), header), length,
1028       kMaxOutgoingPacketSize, buffer.get());
1029   QUICHE_DCHECK(encrypted_length) << ENDPOINT;
1030 
1031   std::unique_ptr<SerializedPacket> serialize_packet(
1032       new SerializedPacket(header.packet_number, header.packet_number_length,
1033                            buffer.release(), encrypted_length,
1034                            /*has_ack=*/false, /*has_stop_waiting=*/false));
1035 
1036   serialize_packet->release_encrypted_buffer = [](const char* p) {
1037     delete[] p;
1038   };
1039   serialize_packet->encryption_level = packet_.encryption_level;
1040   serialize_packet->transmission_type = NOT_RETRANSMISSION;
1041 
1042   return serialize_packet;
1043 }
1044 
BuildPaddedPathChallengePacket(const QuicPacketHeader & header,char * buffer,size_t packet_length,const QuicPathFrameBuffer & payload,EncryptionLevel level)1045 size_t QuicPacketCreator::BuildPaddedPathChallengePacket(
1046     const QuicPacketHeader& header, char* buffer, size_t packet_length,
1047     const QuicPathFrameBuffer& payload, EncryptionLevel level) {
1048   QUICHE_DCHECK(VersionHasIetfQuicFrames(framer_->transport_version()))
1049       << ENDPOINT;
1050   QuicFrames frames;
1051 
1052   // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1053   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, payload)));
1054 
1055   if (debug_delegate_ != nullptr) {
1056     debug_delegate_->OnFrameAddedToPacket(frames.back());
1057   }
1058 
1059   // Add padding to the rest of the packet in order to assess Path MTU
1060   // characteristics.
1061   QuicPaddingFrame padding_frame;
1062   frames.push_back(QuicFrame(padding_frame));
1063 
1064   return framer_->BuildDataPacket(header, frames, buffer, packet_length, level);
1065 }
1066 
BuildPathResponsePacket(const QuicPacketHeader & header,char * buffer,size_t packet_length,const quiche::QuicheCircularDeque<QuicPathFrameBuffer> & payloads,const bool is_padded,EncryptionLevel level)1067 size_t QuicPacketCreator::BuildPathResponsePacket(
1068     const QuicPacketHeader& header, char* buffer, size_t packet_length,
1069     const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads,
1070     const bool is_padded, EncryptionLevel level) {
1071   if (payloads.empty()) {
1072     QUIC_BUG(quic_bug_12398_14)
1073         << ENDPOINT
1074         << "Attempt to generate connectivity response with no request payloads";
1075     return 0;
1076   }
1077   QUICHE_DCHECK(VersionHasIetfQuicFrames(framer_->transport_version()))
1078       << ENDPOINT;
1079 
1080   QuicFrames frames;
1081   for (const QuicPathFrameBuffer& payload : payloads) {
1082     // Note that the control frame ID can be 0 since this is not retransmitted.
1083     frames.push_back(QuicFrame(QuicPathResponseFrame(0, payload)));
1084     if (debug_delegate_ != nullptr) {
1085       debug_delegate_->OnFrameAddedToPacket(frames.back());
1086     }
1087   }
1088 
1089   if (is_padded) {
1090     // Add padding to the rest of the packet in order to assess Path MTU
1091     // characteristics.
1092     QuicPaddingFrame padding_frame;
1093     frames.push_back(QuicFrame(padding_frame));
1094   }
1095 
1096   return framer_->BuildDataPacket(header, frames, buffer, packet_length, level);
1097 }
1098 
BuildConnectivityProbingPacket(const QuicPacketHeader & header,char * buffer,size_t packet_length,EncryptionLevel level)1099 size_t QuicPacketCreator::BuildConnectivityProbingPacket(
1100     const QuicPacketHeader& header, char* buffer, size_t packet_length,
1101     EncryptionLevel level) {
1102   QuicFrames frames;
1103 
1104   // Write a PING frame, which has no data payload.
1105   QuicPingFrame ping_frame;
1106   frames.push_back(QuicFrame(ping_frame));
1107 
1108   // Add padding to the rest of the packet.
1109   QuicPaddingFrame padding_frame;
1110   frames.push_back(QuicFrame(padding_frame));
1111 
1112   return framer_->BuildDataPacket(header, frames, buffer, packet_length, level);
1113 }
1114 
SerializeCoalescedPacket(const QuicCoalescedPacket & coalesced,char * buffer,size_t buffer_len)1115 size_t QuicPacketCreator::SerializeCoalescedPacket(
1116     const QuicCoalescedPacket& coalesced, char* buffer, size_t buffer_len) {
1117   if (HasPendingFrames()) {
1118     QUIC_BUG(quic_bug_10752_18)
1119         << ENDPOINT << "Try to serialize coalesced packet with pending frames";
1120     return 0;
1121   }
1122   RemoveSoftMaxPacketLength();
1123   QUIC_BUG_IF(quic_bug_12398_15, coalesced.length() == 0)
1124       << ENDPOINT << "Attempt to serialize empty coalesced packet";
1125   size_t packet_length = 0;
1126   size_t initial_length = 0;
1127   size_t padding_size = 0;
1128   if (coalesced.initial_packet() != nullptr) {
1129     // Padding coalesced packet containing initial packet to full.
1130     padding_size = coalesced.max_packet_length() - coalesced.length();
1131     if (framer_->perspective() == Perspective::IS_SERVER &&
1132         QuicUtils::ContainsFrameType(
1133             coalesced.initial_packet()->retransmittable_frames,
1134             CONNECTION_CLOSE_FRAME)) {
1135       // Do not pad server initial connection close packet.
1136       padding_size = 0;
1137     }
1138     initial_length = ReserializeInitialPacketInCoalescedPacket(
1139         *coalesced.initial_packet(), padding_size, buffer, buffer_len);
1140     if (initial_length == 0) {
1141       QUIC_BUG(quic_bug_10752_19)
1142           << ENDPOINT
1143           << "Failed to reserialize ENCRYPTION_INITIAL packet in "
1144              "coalesced packet";
1145       return 0;
1146     }
1147     QUIC_BUG_IF(quic_reserialize_initial_packet_unexpected_size,
1148                 coalesced.initial_packet()->encrypted_length + padding_size !=
1149                     initial_length)
1150         << "Reserialize initial packet in coalescer has unexpected size, "
1151            "original_length: "
1152         << coalesced.initial_packet()->encrypted_length
1153         << ", coalesced.max_packet_length: " << coalesced.max_packet_length()
1154         << ", coalesced.length: " << coalesced.length()
1155         << ", padding_size: " << padding_size
1156         << ", serialized_length: " << initial_length
1157         << ", retransmittable frames: "
1158         << QuicFramesToString(
1159                coalesced.initial_packet()->retransmittable_frames)
1160         << ", nonretransmittable frames: "
1161         << QuicFramesToString(
1162                coalesced.initial_packet()->nonretransmittable_frames);
1163     buffer += initial_length;
1164     buffer_len -= initial_length;
1165     packet_length += initial_length;
1166   }
1167   size_t length_copied = 0;
1168   if (!coalesced.CopyEncryptedBuffers(buffer, buffer_len, &length_copied)) {
1169     QUIC_BUG(quic_serialize_coalesced_packet_copy_failure)
1170         << "SerializeCoalescedPacket failed. buffer_len:" << buffer_len
1171         << ", initial_length:" << initial_length
1172         << ", padding_size: " << padding_size
1173         << ", length_copied:" << length_copied
1174         << ", coalesced.length:" << coalesced.length()
1175         << ", coalesced.max_packet_length:" << coalesced.max_packet_length()
1176         << ", coalesced.packet_lengths:"
1177         << absl::StrJoin(coalesced.packet_lengths(), ":");
1178     return 0;
1179   }
1180   packet_length += length_copied;
1181   QUIC_DVLOG(1) << ENDPOINT
1182                 << "Successfully serialized coalesced packet of length: "
1183                 << packet_length;
1184   return packet_length;
1185 }
1186 
1187 // TODO(b/74062209): Make this a public method of framer?
NoPacket()1188 SerializedPacket QuicPacketCreator::NoPacket() {
1189   return SerializedPacket(QuicPacketNumber(), PACKET_1BYTE_PACKET_NUMBER,
1190                           nullptr, 0, false, false);
1191 }
1192 
GetDestinationConnectionId() const1193 QuicConnectionId QuicPacketCreator::GetDestinationConnectionId() const {
1194   if (framer_->perspective() == Perspective::IS_SERVER) {
1195     return client_connection_id_;
1196   }
1197   return server_connection_id_;
1198 }
1199 
GetSourceConnectionId() const1200 QuicConnectionId QuicPacketCreator::GetSourceConnectionId() const {
1201   if (framer_->perspective() == Perspective::IS_CLIENT) {
1202     return client_connection_id_;
1203   }
1204   return server_connection_id_;
1205 }
1206 
GetDestinationConnectionIdIncluded() const1207 QuicConnectionIdIncluded QuicPacketCreator::GetDestinationConnectionIdIncluded()
1208     const {
1209   // In versions that do not support client connection IDs, the destination
1210   // connection ID is only sent from client to server.
1211   return (framer_->perspective() == Perspective::IS_CLIENT ||
1212           framer_->version().SupportsClientConnectionIds())
1213              ? CONNECTION_ID_PRESENT
1214              : CONNECTION_ID_ABSENT;
1215 }
1216 
GetSourceConnectionIdIncluded() const1217 QuicConnectionIdIncluded QuicPacketCreator::GetSourceConnectionIdIncluded()
1218     const {
1219   // Long header packets sent by server include source connection ID.
1220   // Ones sent by the client only include source connection ID if the version
1221   // supports client connection IDs.
1222   if (HasIetfLongHeader() &&
1223       (framer_->perspective() == Perspective::IS_SERVER ||
1224        framer_->version().SupportsClientConnectionIds())) {
1225     return CONNECTION_ID_PRESENT;
1226   }
1227   if (framer_->perspective() == Perspective::IS_SERVER) {
1228     return server_connection_id_included_;
1229   }
1230   return CONNECTION_ID_ABSENT;
1231 }
1232 
GetDestinationConnectionIdLength() const1233 uint8_t QuicPacketCreator::GetDestinationConnectionIdLength() const {
1234   QUICHE_DCHECK(QuicUtils::IsConnectionIdValidForVersion(server_connection_id_,
1235                                                          transport_version()))
1236       << ENDPOINT;
1237   return GetDestinationConnectionIdIncluded() == CONNECTION_ID_PRESENT
1238              ? GetDestinationConnectionId().length()
1239              : 0;
1240 }
1241 
GetSourceConnectionIdLength() const1242 uint8_t QuicPacketCreator::GetSourceConnectionIdLength() const {
1243   QUICHE_DCHECK(QuicUtils::IsConnectionIdValidForVersion(server_connection_id_,
1244                                                          transport_version()))
1245       << ENDPOINT;
1246   return GetSourceConnectionIdIncluded() == CONNECTION_ID_PRESENT
1247              ? GetSourceConnectionId().length()
1248              : 0;
1249 }
1250 
GetPacketNumberLength() const1251 QuicPacketNumberLength QuicPacketCreator::GetPacketNumberLength() const {
1252   if (HasIetfLongHeader() &&
1253       !framer_->version().SendsVariableLengthPacketNumberInLongHeader()) {
1254     return PACKET_4BYTE_PACKET_NUMBER;
1255   }
1256   return packet_.packet_number_length;
1257 }
1258 
PacketHeaderSize() const1259 size_t QuicPacketCreator::PacketHeaderSize() const {
1260   return GetPacketHeaderSize(
1261       framer_->transport_version(), GetDestinationConnectionIdLength(),
1262       GetSourceConnectionIdLength(), IncludeVersionInHeader(),
1263       IncludeNonceInPublicHeader(), GetPacketNumberLength(),
1264       GetRetryTokenLengthLength(), GetRetryToken().length(), GetLengthLength());
1265 }
1266 
1267 quiche::QuicheVariableLengthIntegerLength
GetRetryTokenLengthLength() const1268 QuicPacketCreator::GetRetryTokenLengthLength() const {
1269   if (QuicVersionHasLongHeaderLengths(framer_->transport_version()) &&
1270       HasIetfLongHeader() &&
1271       EncryptionlevelToLongHeaderType(packet_.encryption_level) == INITIAL) {
1272     return QuicDataWriter::GetVarInt62Len(GetRetryToken().length());
1273   }
1274   return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0;
1275 }
1276 
GetRetryToken() const1277 absl::string_view QuicPacketCreator::GetRetryToken() const {
1278   if (QuicVersionHasLongHeaderLengths(framer_->transport_version()) &&
1279       HasIetfLongHeader() &&
1280       EncryptionlevelToLongHeaderType(packet_.encryption_level) == INITIAL) {
1281     return retry_token_;
1282   }
1283   return absl::string_view();
1284 }
1285 
SetRetryToken(absl::string_view retry_token)1286 void QuicPacketCreator::SetRetryToken(absl::string_view retry_token) {
1287   retry_token_ = std::string(retry_token);
1288 }
1289 
ConsumeRetransmittableControlFrame(const QuicFrame & frame)1290 bool QuicPacketCreator::ConsumeRetransmittableControlFrame(
1291     const QuicFrame& frame) {
1292   QUIC_BUG_IF(quic_bug_12398_16, IsControlFrame(frame.type) &&
1293                                      !GetControlFrameId(frame) &&
1294                                      frame.type != PING_FRAME)
1295       << ENDPOINT
1296       << "Adding a control frame with no control frame id: " << frame;
1297   QUICHE_DCHECK(QuicUtils::IsRetransmittableFrame(frame.type))
1298       << ENDPOINT << frame;
1299   MaybeBundleAckOpportunistically();
1300   if (HasPendingFrames()) {
1301     if (AddFrame(frame, next_transmission_type_)) {
1302       // There is pending frames and current frame fits.
1303       return true;
1304     }
1305   }
1306   QUICHE_DCHECK(!HasPendingFrames()) << ENDPOINT;
1307   if (frame.type != PING_FRAME && frame.type != CONNECTION_CLOSE_FRAME &&
1308       !delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA,
1309                                        NOT_HANDSHAKE)) {
1310     // Do not check congestion window for ping or connection close frames.
1311     return false;
1312   }
1313   const bool success = AddFrame(frame, next_transmission_type_);
1314   QUIC_BUG_IF(quic_bug_10752_20, !success)
1315       << ENDPOINT << "Failed to add frame:" << frame
1316       << " transmission_type:" << next_transmission_type_;
1317   return success;
1318 }
1319 
ConsumeData(QuicStreamId id,size_t write_length,QuicStreamOffset offset,StreamSendingState state)1320 QuicConsumedData QuicPacketCreator::ConsumeData(QuicStreamId id,
1321                                                 size_t write_length,
1322                                                 QuicStreamOffset offset,
1323                                                 StreamSendingState state) {
1324   QUIC_BUG_IF(quic_bug_10752_21, !flusher_attached_)
1325       << ENDPOINT
1326       << "Packet flusher is not attached when "
1327          "generator tries to write stream data.";
1328   bool has_handshake = QuicUtils::IsCryptoStreamId(transport_version(), id);
1329   MaybeBundleAckOpportunistically();
1330   bool fin = state != NO_FIN;
1331   QUIC_BUG_IF(quic_bug_12398_17, has_handshake && fin)
1332       << ENDPOINT << "Handshake packets should never send a fin";
1333   // To make reasoning about crypto frames easier, we don't combine them with
1334   // other retransmittable frames in a single packet.
1335   if (has_handshake && HasPendingRetransmittableFrames()) {
1336     FlushCurrentPacket();
1337   }
1338 
1339   size_t total_bytes_consumed = 0;
1340   bool fin_consumed = false;
1341 
1342   if (!HasRoomForStreamFrame(id, offset, write_length)) {
1343     FlushCurrentPacket();
1344   }
1345 
1346   if (!fin && (write_length == 0)) {
1347     QUIC_BUG(quic_bug_10752_22)
1348         << ENDPOINT << "Attempt to consume empty data without FIN.";
1349     return QuicConsumedData(0, false);
1350   }
1351   // We determine if we can enter the fast path before executing
1352   // the slow path loop.
1353   bool run_fast_path =
1354       !has_handshake && state != FIN_AND_PADDING && !HasPendingFrames() &&
1355       write_length - total_bytes_consumed > kMaxOutgoingPacketSize &&
1356       latched_hard_max_packet_length_ == 0;
1357 
1358   while (!run_fast_path &&
1359          (has_handshake || delegate_->ShouldGeneratePacket(
1360                                HAS_RETRANSMITTABLE_DATA, NOT_HANDSHAKE))) {
1361     QuicFrame frame;
1362     bool needs_full_padding =
1363         has_handshake && fully_pad_crypto_handshake_packets_;
1364 
1365     if (!ConsumeDataToFillCurrentPacket(id, write_length - total_bytes_consumed,
1366                                         offset + total_bytes_consumed, fin,
1367                                         needs_full_padding,
1368                                         next_transmission_type_, &frame)) {
1369       // The creator is always flushed if there's not enough room for a new
1370       // stream frame before ConsumeData, so ConsumeData should always succeed.
1371       QUIC_BUG(quic_bug_10752_23)
1372           << ENDPOINT << "Failed to ConsumeData, stream:" << id;
1373       return QuicConsumedData(0, false);
1374     }
1375 
1376     // A stream frame is created and added.
1377     size_t bytes_consumed = frame.stream_frame.data_length;
1378     total_bytes_consumed += bytes_consumed;
1379     fin_consumed = fin && total_bytes_consumed == write_length;
1380     if (fin_consumed && state == FIN_AND_PADDING) {
1381       AddRandomPadding();
1382     }
1383     QUICHE_DCHECK(total_bytes_consumed == write_length ||
1384                   (bytes_consumed > 0 && HasPendingFrames()))
1385         << ENDPOINT;
1386 
1387     if (total_bytes_consumed == write_length) {
1388       // We're done writing the data. Exit the loop.
1389       // We don't make this a precondition because we could have 0 bytes of data
1390       // if we're simply writing a fin.
1391       break;
1392     }
1393     FlushCurrentPacket();
1394 
1395     run_fast_path =
1396         !has_handshake && state != FIN_AND_PADDING && !HasPendingFrames() &&
1397         write_length - total_bytes_consumed > kMaxOutgoingPacketSize &&
1398         latched_hard_max_packet_length_ == 0;
1399   }
1400 
1401   if (run_fast_path) {
1402     return ConsumeDataFastPath(id, write_length, offset, state != NO_FIN,
1403                                total_bytes_consumed);
1404   }
1405 
1406   // Don't allow the handshake to be bundled with other retransmittable frames.
1407   if (has_handshake) {
1408     FlushCurrentPacket();
1409   }
1410 
1411   return QuicConsumedData(total_bytes_consumed, fin_consumed);
1412 }
1413 
ConsumeDataFastPath(QuicStreamId id,size_t write_length,QuicStreamOffset offset,bool fin,size_t total_bytes_consumed)1414 QuicConsumedData QuicPacketCreator::ConsumeDataFastPath(
1415     QuicStreamId id, size_t write_length, QuicStreamOffset offset, bool fin,
1416     size_t total_bytes_consumed) {
1417   QUICHE_DCHECK(!QuicUtils::IsCryptoStreamId(transport_version(), id))
1418       << ENDPOINT;
1419   if (AttemptingToSendUnencryptedStreamData()) {
1420     return QuicConsumedData(total_bytes_consumed,
1421                             fin && (total_bytes_consumed == write_length));
1422   }
1423 
1424   while (total_bytes_consumed < write_length &&
1425          delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA,
1426                                          NOT_HANDSHAKE)) {
1427     // Serialize and encrypt the packet.
1428     size_t bytes_consumed = 0;
1429     CreateAndSerializeStreamFrame(id, write_length, total_bytes_consumed,
1430                                   offset + total_bytes_consumed, fin,
1431                                   next_transmission_type_, &bytes_consumed);
1432     if (bytes_consumed == 0) {
1433       const std::string error_details =
1434           "Failed in CreateAndSerializeStreamFrame.";
1435       QUIC_BUG(quic_bug_10752_24) << ENDPOINT << error_details;
1436       delegate_->OnUnrecoverableError(QUIC_FAILED_TO_SERIALIZE_PACKET,
1437                                       error_details);
1438       break;
1439     }
1440     total_bytes_consumed += bytes_consumed;
1441   }
1442 
1443   return QuicConsumedData(total_bytes_consumed,
1444                           fin && (total_bytes_consumed == write_length));
1445 }
1446 
ConsumeCryptoData(EncryptionLevel level,size_t write_length,QuicStreamOffset offset)1447 size_t QuicPacketCreator::ConsumeCryptoData(EncryptionLevel level,
1448                                             size_t write_length,
1449                                             QuicStreamOffset offset) {
1450   QUIC_DVLOG(2) << ENDPOINT << "ConsumeCryptoData " << level << " write_length "
1451                 << write_length << " offset " << offset;
1452   QUIC_BUG_IF(quic_bug_10752_25, !flusher_attached_)
1453       << ENDPOINT
1454       << "Packet flusher is not attached when "
1455          "generator tries to write crypto data.";
1456   MaybeBundleAckOpportunistically();
1457   // To make reasoning about crypto frames easier, we don't combine them with
1458   // other retransmittable frames in a single packet.
1459   // TODO(nharper): Once we have separate packet number spaces, everything
1460   // should be driven by encryption level, and we should stop flushing in this
1461   // spot.
1462   if (HasPendingRetransmittableFrames()) {
1463     FlushCurrentPacket();
1464   }
1465 
1466   size_t total_bytes_consumed = 0;
1467 
1468   while (
1469       total_bytes_consumed < write_length &&
1470       delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, IS_HANDSHAKE)) {
1471     QuicFrame frame;
1472     if (!ConsumeCryptoDataToFillCurrentPacket(
1473             level, write_length - total_bytes_consumed,
1474             offset + total_bytes_consumed, fully_pad_crypto_handshake_packets_,
1475             next_transmission_type_, &frame)) {
1476       // The only pending data in the packet is non-retransmittable frames.
1477       // I'm assuming here that they won't occupy so much of the packet that a
1478       // CRYPTO frame won't fit.
1479       QUIC_BUG_IF(quic_bug_10752_26, !HasSoftMaxPacketLength()) << absl::StrCat(
1480           ENDPOINT, "Failed to ConsumeCryptoData at level ", level,
1481           ", pending_frames: ", GetPendingFramesInfo(),
1482           ", has_soft_max_packet_length: ", HasSoftMaxPacketLength(),
1483           ", max_packet_length: ", max_packet_length_, ", transmission_type: ",
1484           TransmissionTypeToString(next_transmission_type_),
1485           ", packet_number: ", packet_number().ToString());
1486       return 0;
1487     }
1488     total_bytes_consumed += frame.crypto_frame->data_length;
1489     FlushCurrentPacket();
1490   }
1491 
1492   // Don't allow the handshake to be bundled with other retransmittable frames.
1493   FlushCurrentPacket();
1494 
1495   return total_bytes_consumed;
1496 }
1497 
GenerateMtuDiscoveryPacket(QuicByteCount target_mtu)1498 void QuicPacketCreator::GenerateMtuDiscoveryPacket(QuicByteCount target_mtu) {
1499   // MTU discovery frames must be sent by themselves.
1500   if (!CanSetMaxPacketLength()) {
1501     QUIC_BUG(quic_bug_10752_27)
1502         << ENDPOINT
1503         << "MTU discovery packets should only be sent when no other "
1504         << "frames needs to be sent.";
1505     return;
1506   }
1507   const QuicByteCount current_mtu = max_packet_length();
1508 
1509   // The MTU discovery frame is allocated on the stack, since it is going to be
1510   // serialized within this function.
1511   QuicMtuDiscoveryFrame mtu_discovery_frame;
1512   QuicFrame frame(mtu_discovery_frame);
1513 
1514   // Send the probe packet with the new length.
1515   SetMaxPacketLength(target_mtu);
1516   const bool success = AddPaddedSavedFrame(frame, next_transmission_type_);
1517   FlushCurrentPacket();
1518   // The only reason AddFrame can fail is that the packet is too full to fit in
1519   // a ping.  This is not possible for any sane MTU.
1520   QUIC_BUG_IF(quic_bug_10752_28, !success)
1521       << ENDPOINT << "Failed to send path MTU target_mtu:" << target_mtu
1522       << " transmission_type:" << next_transmission_type_;
1523 
1524   // Reset the packet length back.
1525   SetMaxPacketLength(current_mtu);
1526 }
1527 
MaybeBundleAckOpportunistically()1528 void QuicPacketCreator::MaybeBundleAckOpportunistically() {
1529   if (has_ack()) {
1530     // Ack already queued, nothing to do.
1531     return;
1532   }
1533   if (!delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
1534                                        NOT_HANDSHAKE)) {
1535     return;
1536   }
1537   const bool flushed =
1538       FlushAckFrame(delegate_->MaybeBundleAckOpportunistically());
1539   QUIC_BUG_IF(quic_bug_10752_29, !flushed)
1540       << ENDPOINT << "Failed to flush ACK frame. encryption_level:"
1541       << packet_.encryption_level;
1542 }
1543 
FlushAckFrame(const QuicFrames & frames)1544 bool QuicPacketCreator::FlushAckFrame(const QuicFrames& frames) {
1545   QUIC_BUG_IF(quic_bug_10752_30, !flusher_attached_)
1546       << ENDPOINT
1547       << "Packet flusher is not attached when "
1548          "generator tries to send ACK frame.";
1549   // MaybeBundleAckOpportunistically could be called nestedly when sending a
1550   // control frame causing another control frame to be sent.
1551   QUIC_BUG_IF(quic_bug_12398_18, !frames.empty() && has_ack())
1552       << ENDPOINT << "Trying to flush " << quiche::PrintElements(frames)
1553       << " when there is ACK queued";
1554   for (const auto& frame : frames) {
1555     QUICHE_DCHECK(frame.type == ACK_FRAME || frame.type == STOP_WAITING_FRAME)
1556         << ENDPOINT;
1557     if (HasPendingFrames()) {
1558       if (AddFrame(frame, next_transmission_type_)) {
1559         // There is pending frames and current frame fits.
1560         continue;
1561       }
1562     }
1563     QUICHE_DCHECK(!HasPendingFrames()) << ENDPOINT;
1564     // There is no pending frames, consult the delegate whether a packet can be
1565     // generated.
1566     if (!delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
1567                                          NOT_HANDSHAKE)) {
1568       return false;
1569     }
1570     const bool success = AddFrame(frame, next_transmission_type_);
1571     QUIC_BUG_IF(quic_bug_10752_31, !success)
1572         << ENDPOINT << "Failed to flush " << frame;
1573   }
1574   return true;
1575 }
1576 
AddRandomPadding()1577 void QuicPacketCreator::AddRandomPadding() {
1578   AddPendingPadding(random_->RandUint64() % kMaxNumRandomPaddingBytes + 1);
1579 }
1580 
AttachPacketFlusher()1581 void QuicPacketCreator::AttachPacketFlusher() {
1582   flusher_attached_ = true;
1583   if (!write_start_packet_number_.IsInitialized()) {
1584     write_start_packet_number_ = NextSendingPacketNumber();
1585   }
1586 }
1587 
Flush()1588 void QuicPacketCreator::Flush() {
1589   FlushCurrentPacket();
1590   SendRemainingPendingPadding();
1591   flusher_attached_ = false;
1592   if (GetQuicFlag(quic_export_write_path_stats_at_server)) {
1593     if (!write_start_packet_number_.IsInitialized()) {
1594       QUIC_BUG(quic_bug_10752_32)
1595           << ENDPOINT << "write_start_packet_number is not initialized";
1596       return;
1597     }
1598     QUIC_SERVER_HISTOGRAM_COUNTS(
1599         "quic_server_num_written_packets_per_write",
1600         NextSendingPacketNumber() - write_start_packet_number_, 1, 200, 50,
1601         "Number of QUIC packets written per write operation");
1602   }
1603   write_start_packet_number_.Clear();
1604 }
1605 
SendRemainingPendingPadding()1606 void QuicPacketCreator::SendRemainingPendingPadding() {
1607   while (
1608       pending_padding_bytes() > 0 && !HasPendingFrames() &&
1609       delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)) {
1610     FlushCurrentPacket();
1611   }
1612 }
1613 
SetServerConnectionIdLength(uint32_t length)1614 void QuicPacketCreator::SetServerConnectionIdLength(uint32_t length) {
1615   if (length == 0) {
1616     SetServerConnectionIdIncluded(CONNECTION_ID_ABSENT);
1617   } else {
1618     SetServerConnectionIdIncluded(CONNECTION_ID_PRESENT);
1619   }
1620 }
1621 
SetTransmissionType(TransmissionType type)1622 void QuicPacketCreator::SetTransmissionType(TransmissionType type) {
1623   next_transmission_type_ = type;
1624 }
1625 
AddMessageFrame(QuicMessageId message_id,absl::Span<quiche::QuicheMemSlice> message)1626 MessageStatus QuicPacketCreator::AddMessageFrame(
1627     QuicMessageId message_id, absl::Span<quiche::QuicheMemSlice> message) {
1628   QUIC_BUG_IF(quic_bug_10752_33, !flusher_attached_)
1629       << ENDPOINT
1630       << "Packet flusher is not attached when "
1631          "generator tries to add message frame.";
1632   MaybeBundleAckOpportunistically();
1633   const QuicByteCount message_length = MemSliceSpanTotalSize(message);
1634   if (message_length > GetCurrentLargestMessagePayload()) {
1635     return MESSAGE_STATUS_TOO_LARGE;
1636   }
1637   if (!HasRoomForMessageFrame(message_length)) {
1638     FlushCurrentPacket();
1639   }
1640   QuicMessageFrame* frame = new QuicMessageFrame(message_id, message);
1641   const bool success = AddFrame(QuicFrame(frame), next_transmission_type_);
1642   if (!success) {
1643     QUIC_BUG(quic_bug_10752_34)
1644         << ENDPOINT << "Failed to send message " << message_id;
1645     delete frame;
1646     return MESSAGE_STATUS_INTERNAL_ERROR;
1647   }
1648   QUICHE_DCHECK_EQ(MemSliceSpanTotalSize(message),
1649                    0u);  // Ensure the old slices are empty.
1650   return MESSAGE_STATUS_SUCCESS;
1651 }
1652 
GetLengthLength() const1653 quiche::QuicheVariableLengthIntegerLength QuicPacketCreator::GetLengthLength()
1654     const {
1655   if (QuicVersionHasLongHeaderLengths(framer_->transport_version()) &&
1656       HasIetfLongHeader()) {
1657     QuicLongHeaderType long_header_type =
1658         EncryptionlevelToLongHeaderType(packet_.encryption_level);
1659     if (long_header_type == INITIAL || long_header_type == ZERO_RTT_PROTECTED ||
1660         long_header_type == HANDSHAKE) {
1661       return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
1662     }
1663   }
1664   return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0;
1665 }
1666 
FillPacketHeader(QuicPacketHeader * header)1667 void QuicPacketCreator::FillPacketHeader(QuicPacketHeader* header) {
1668   header->destination_connection_id = GetDestinationConnectionId();
1669   header->destination_connection_id_included =
1670       GetDestinationConnectionIdIncluded();
1671   header->source_connection_id = GetSourceConnectionId();
1672   header->source_connection_id_included = GetSourceConnectionIdIncluded();
1673   header->reset_flag = false;
1674   header->version_flag = IncludeVersionInHeader();
1675   if (IncludeNonceInPublicHeader()) {
1676     QUICHE_DCHECK_EQ(Perspective::IS_SERVER, framer_->perspective())
1677         << ENDPOINT;
1678     header->nonce = &diversification_nonce_;
1679   } else {
1680     header->nonce = nullptr;
1681   }
1682   packet_.packet_number = NextSendingPacketNumber();
1683   header->packet_number = packet_.packet_number;
1684   header->packet_number_length = GetPacketNumberLength();
1685   header->retry_token_length_length = GetRetryTokenLengthLength();
1686   header->retry_token = GetRetryToken();
1687   header->length_length = GetLengthLength();
1688   header->remaining_packet_length = 0;
1689   if (!HasIetfLongHeader()) {
1690     return;
1691   }
1692   header->long_packet_type =
1693       EncryptionlevelToLongHeaderType(packet_.encryption_level);
1694 }
1695 
GetSerializedFrameLength(const QuicFrame & frame)1696 size_t QuicPacketCreator::GetSerializedFrameLength(const QuicFrame& frame) {
1697   size_t serialized_frame_length = framer_->GetSerializedFrameLength(
1698       frame, BytesFree(), queued_frames_.empty(),
1699       /* last_frame_in_packet= */ true, GetPacketNumberLength());
1700   if (!framer_->version().HasHeaderProtection() ||
1701       serialized_frame_length == 0) {
1702     return serialized_frame_length;
1703   }
1704   // Calculate frame bytes and bytes free with this frame added.
1705   const size_t frame_bytes = PacketSize() - PacketHeaderSize() +
1706                              ExpansionOnNewFrame() + serialized_frame_length;
1707   if (frame_bytes >=
1708       MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength())) {
1709     // No extra bytes is needed.
1710     return serialized_frame_length;
1711   }
1712   if (BytesFree() < serialized_frame_length) {
1713     QUIC_BUG(quic_bug_10752_35) << ENDPOINT << "Frame does not fit: " << frame;
1714     return 0;
1715   }
1716   // Please note bytes_free does not take |frame|'s expansion into account.
1717   size_t bytes_free = BytesFree() - serialized_frame_length;
1718   // Extra bytes needed (this is NOT padding needed) should be at least 1
1719   // padding + expansion.
1720   const size_t extra_bytes_needed = std::max(
1721       1 + ExpansionOnNewFrameWithLastFrame(frame, framer_->transport_version()),
1722       MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength()) -
1723           frame_bytes);
1724   if (bytes_free < extra_bytes_needed) {
1725     // This frame does not fit.
1726     return 0;
1727   }
1728   return serialized_frame_length;
1729 }
1730 
AddFrame(const QuicFrame & frame,TransmissionType transmission_type)1731 bool QuicPacketCreator::AddFrame(const QuicFrame& frame,
1732                                  TransmissionType transmission_type) {
1733   QUIC_DVLOG(1) << ENDPOINT << "Adding frame with transmission type "
1734                 << transmission_type << ": " << frame;
1735   if (frame.type == STREAM_FRAME &&
1736       !QuicUtils::IsCryptoStreamId(framer_->transport_version(),
1737                                    frame.stream_frame.stream_id) &&
1738       AttemptingToSendUnencryptedStreamData()) {
1739     return false;
1740   }
1741 
1742   // Sanity check to ensure we don't send frames at the wrong encryption level.
1743   QUICHE_DCHECK(
1744       packet_.encryption_level == ENCRYPTION_ZERO_RTT ||
1745       packet_.encryption_level == ENCRYPTION_FORWARD_SECURE ||
1746       (frame.type != GOAWAY_FRAME && frame.type != WINDOW_UPDATE_FRAME &&
1747        frame.type != HANDSHAKE_DONE_FRAME &&
1748        frame.type != NEW_CONNECTION_ID_FRAME &&
1749        frame.type != MAX_STREAMS_FRAME && frame.type != STREAMS_BLOCKED_FRAME &&
1750        frame.type != PATH_RESPONSE_FRAME &&
1751        frame.type != PATH_CHALLENGE_FRAME && frame.type != STOP_SENDING_FRAME &&
1752        frame.type != MESSAGE_FRAME && frame.type != NEW_TOKEN_FRAME &&
1753        frame.type != RETIRE_CONNECTION_ID_FRAME &&
1754        frame.type != ACK_FREQUENCY_FRAME))
1755       << ENDPOINT << frame.type << " not allowed at "
1756       << packet_.encryption_level;
1757 
1758   if (frame.type == STREAM_FRAME) {
1759     if (MaybeCoalesceStreamFrame(frame.stream_frame)) {
1760       LogCoalesceStreamFrameStatus(true);
1761       return true;
1762     } else {
1763       LogCoalesceStreamFrameStatus(false);
1764     }
1765   }
1766 
1767   // If this is an ACK frame, validate that it is non-empty and that
1768   // largest_acked matches the max packet number.
1769   QUICHE_DCHECK(frame.type != ACK_FRAME || (!frame.ack_frame->packets.Empty() &&
1770                                             frame.ack_frame->packets.Max() ==
1771                                                 frame.ack_frame->largest_acked))
1772       << ENDPOINT << "Invalid ACK frame: " << frame;
1773 
1774   size_t frame_len = GetSerializedFrameLength(frame);
1775   if (frame_len == 0 && RemoveSoftMaxPacketLength()) {
1776     // Remove soft max_packet_length and retry.
1777     frame_len = GetSerializedFrameLength(frame);
1778   }
1779   if (frame_len == 0) {
1780     QUIC_DVLOG(1) << ENDPOINT
1781                   << "Flushing because current open packet is full when adding "
1782                   << frame;
1783     FlushCurrentPacket();
1784     return false;
1785   }
1786   if (queued_frames_.empty()) {
1787     packet_size_ = PacketHeaderSize();
1788   }
1789   QUICHE_DCHECK_LT(0u, packet_size_) << ENDPOINT;
1790 
1791   packet_size_ += ExpansionOnNewFrame() + frame_len;
1792 
1793   if (QuicUtils::IsRetransmittableFrame(frame.type)) {
1794     packet_.retransmittable_frames.push_back(frame);
1795     queued_frames_.push_back(frame);
1796     if (QuicUtils::IsHandshakeFrame(frame, framer_->transport_version())) {
1797       packet_.has_crypto_handshake = IS_HANDSHAKE;
1798     }
1799   } else {
1800     if (frame.type == PADDING_FRAME &&
1801         frame.padding_frame.num_padding_bytes == -1) {
1802       // Populate the actual length of full padding frame, such that one can
1803       // know how much padding is actually added.
1804       packet_.nonretransmittable_frames.push_back(
1805           QuicFrame(QuicPaddingFrame(frame_len)));
1806     } else {
1807       packet_.nonretransmittable_frames.push_back(frame);
1808     }
1809     queued_frames_.push_back(frame);
1810   }
1811 
1812   if (frame.type == ACK_FRAME) {
1813     packet_.has_ack = true;
1814     packet_.largest_acked = LargestAcked(*frame.ack_frame);
1815     if (frame.ack_frame->ecn_counters.has_value()) {
1816       packet_.has_ack_ecn = true;
1817     }
1818   } else if (frame.type == STOP_WAITING_FRAME) {
1819     packet_.has_stop_waiting = true;
1820   } else if (frame.type == ACK_FREQUENCY_FRAME) {
1821     packet_.has_ack_frequency = true;
1822   } else if (frame.type == MESSAGE_FRAME) {
1823     packet_.has_message = true;
1824   }
1825   if (debug_delegate_ != nullptr) {
1826     debug_delegate_->OnFrameAddedToPacket(frame);
1827   }
1828 
1829   if (transmission_type == NOT_RETRANSMISSION) {
1830     packet_.bytes_not_retransmitted.emplace(
1831         packet_.bytes_not_retransmitted.value_or(0) + frame_len);
1832   } else if (QuicUtils::IsRetransmittableFrame(frame.type)) {
1833     // Packet transmission type is determined by the last added retransmittable
1834     // frame of a retransmission type. If a packet has no retransmittable
1835     // retransmission frames, it has type NOT_RETRANSMISSION.
1836     packet_.transmission_type = transmission_type;
1837   }
1838   return true;
1839 }
1840 
MaybeAddExtraPaddingForHeaderProtection()1841 void QuicPacketCreator::MaybeAddExtraPaddingForHeaderProtection() {
1842   if (!framer_->version().HasHeaderProtection() || needs_full_padding_) {
1843     return;
1844   }
1845   const size_t frame_bytes = PacketSize() - PacketHeaderSize();
1846   if (frame_bytes >=
1847       MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength())) {
1848     return;
1849   }
1850   QuicByteCount min_header_protection_padding =
1851       MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength()) -
1852       frame_bytes;
1853   // Update pending_padding_bytes_.
1854   pending_padding_bytes_ =
1855       std::max(pending_padding_bytes_, min_header_protection_padding);
1856 }
1857 
MaybeCoalesceStreamFrame(const QuicStreamFrame & frame)1858 bool QuicPacketCreator::MaybeCoalesceStreamFrame(const QuicStreamFrame& frame) {
1859   if (queued_frames_.empty() || queued_frames_.back().type != STREAM_FRAME) {
1860     return false;
1861   }
1862   QuicStreamFrame* candidate = &queued_frames_.back().stream_frame;
1863   if (candidate->stream_id != frame.stream_id ||
1864       candidate->offset + candidate->data_length != frame.offset ||
1865       frame.data_length > BytesFree()) {
1866     return false;
1867   }
1868   candidate->data_length += frame.data_length;
1869   candidate->fin = frame.fin;
1870 
1871   // The back of retransmittable frames must be the same as the original
1872   // queued frames' back.
1873   QUICHE_DCHECK_EQ(packet_.retransmittable_frames.back().type, STREAM_FRAME)
1874       << ENDPOINT;
1875   QuicStreamFrame* retransmittable =
1876       &packet_.retransmittable_frames.back().stream_frame;
1877   QUICHE_DCHECK_EQ(retransmittable->stream_id, frame.stream_id) << ENDPOINT;
1878   QUICHE_DCHECK_EQ(retransmittable->offset + retransmittable->data_length,
1879                    frame.offset)
1880       << ENDPOINT;
1881   retransmittable->data_length = candidate->data_length;
1882   retransmittable->fin = candidate->fin;
1883   packet_size_ += frame.data_length;
1884   if (debug_delegate_ != nullptr) {
1885     debug_delegate_->OnStreamFrameCoalesced(*candidate);
1886   }
1887   return true;
1888 }
1889 
RemoveSoftMaxPacketLength()1890 bool QuicPacketCreator::RemoveSoftMaxPacketLength() {
1891   if (latched_hard_max_packet_length_ == 0) {
1892     return false;
1893   }
1894   if (!CanSetMaxPacketLength()) {
1895     return false;
1896   }
1897   QUIC_DVLOG(1) << ENDPOINT << "Restoring max packet length to: "
1898                 << latched_hard_max_packet_length_;
1899   SetMaxPacketLength(latched_hard_max_packet_length_);
1900   // Reset latched_max_packet_length_.
1901   latched_hard_max_packet_length_ = 0;
1902   return true;
1903 }
1904 
MaybeAddPadding()1905 void QuicPacketCreator::MaybeAddPadding() {
1906   // The current packet should have no padding bytes because padding is only
1907   // added when this method is called just before the packet is serialized.
1908   if (BytesFreeForPadding() == 0) {
1909     // Don't pad full packets.
1910     return;
1911   }
1912 
1913   if (packet_.fate == COALESCE) {
1914     // Do not add full padding if the packet is going to be coalesced.
1915     needs_full_padding_ = false;
1916   }
1917 
1918   // Header protection requires a minimum plaintext packet size.
1919   MaybeAddExtraPaddingForHeaderProtection();
1920 
1921   QUIC_DVLOG(3) << "MaybeAddPadding for " << packet_.packet_number
1922                 << ": transmission_type:" << packet_.transmission_type
1923                 << ", fate:" << packet_.fate
1924                 << ", needs_full_padding_:" << needs_full_padding_
1925                 << ", pending_padding_bytes_:" << pending_padding_bytes_
1926                 << ", BytesFree:" << BytesFree();
1927 
1928   if (!needs_full_padding_ && pending_padding_bytes_ == 0) {
1929     // Do not need padding.
1930     return;
1931   }
1932 
1933   int padding_bytes = -1;
1934   if (!needs_full_padding_) {
1935     padding_bytes =
1936         std::min<int16_t>(pending_padding_bytes_, BytesFreeForPadding());
1937     pending_padding_bytes_ -= padding_bytes;
1938   }
1939 
1940   if (!queued_frames_.empty()) {
1941     // Insert PADDING before the other frames to avoid adding a length field
1942     // to any trailing STREAM frame.
1943     if (needs_full_padding_) {
1944       padding_bytes = BytesFreeForPadding();
1945     }
1946     // AddFrame cannot be used here because it adds the frame to the end of the
1947     // packet.
1948     QuicFrame frame{QuicPaddingFrame(padding_bytes)};
1949     queued_frames_.insert(queued_frames_.begin(), frame);
1950     packet_size_ += padding_bytes;
1951     packet_.nonretransmittable_frames.push_back(frame);
1952     if (packet_.transmission_type == NOT_RETRANSMISSION) {
1953       packet_.bytes_not_retransmitted.emplace(
1954           packet_.bytes_not_retransmitted.value_or(0) + padding_bytes);
1955     }
1956   } else {
1957     bool success = AddFrame(QuicFrame(QuicPaddingFrame(padding_bytes)),
1958                             packet_.transmission_type);
1959     QUIC_BUG_IF(quic_bug_10752_36, !success)
1960         << ENDPOINT << "Failed to add padding_bytes: " << padding_bytes
1961         << " transmission_type: " << packet_.transmission_type;
1962   }
1963 }
1964 
IncludeNonceInPublicHeader() const1965 bool QuicPacketCreator::IncludeNonceInPublicHeader() const {
1966   return have_diversification_nonce_ &&
1967          packet_.encryption_level == ENCRYPTION_ZERO_RTT;
1968 }
1969 
IncludeVersionInHeader() const1970 bool QuicPacketCreator::IncludeVersionInHeader() const {
1971   if (version().HasIetfInvariantHeader()) {
1972     return packet_.encryption_level < ENCRYPTION_FORWARD_SECURE;
1973   }
1974   return send_version_in_packet_;
1975 }
1976 
AddPendingPadding(QuicByteCount size)1977 void QuicPacketCreator::AddPendingPadding(QuicByteCount size) {
1978   pending_padding_bytes_ += size;
1979   QUIC_DVLOG(3) << "After AddPendingPadding(" << size
1980                 << "), pending_padding_bytes_:" << pending_padding_bytes_;
1981 }
1982 
StreamFrameIsClientHello(const QuicStreamFrame & frame) const1983 bool QuicPacketCreator::StreamFrameIsClientHello(
1984     const QuicStreamFrame& frame) const {
1985   if (framer_->perspective() == Perspective::IS_SERVER ||
1986       !QuicUtils::IsCryptoStreamId(framer_->transport_version(),
1987                                    frame.stream_id)) {
1988     return false;
1989   }
1990   // The ClientHello is always sent with INITIAL encryption.
1991   return packet_.encryption_level == ENCRYPTION_INITIAL;
1992 }
1993 
SetServerConnectionIdIncluded(QuicConnectionIdIncluded server_connection_id_included)1994 void QuicPacketCreator::SetServerConnectionIdIncluded(
1995     QuicConnectionIdIncluded server_connection_id_included) {
1996   QUICHE_DCHECK(server_connection_id_included == CONNECTION_ID_PRESENT ||
1997                 server_connection_id_included == CONNECTION_ID_ABSENT)
1998       << ENDPOINT;
1999   QUICHE_DCHECK(framer_->perspective() == Perspective::IS_SERVER ||
2000                 server_connection_id_included != CONNECTION_ID_ABSENT)
2001       << ENDPOINT;
2002   server_connection_id_included_ = server_connection_id_included;
2003 }
2004 
SetServerConnectionId(QuicConnectionId server_connection_id)2005 void QuicPacketCreator::SetServerConnectionId(
2006     QuicConnectionId server_connection_id) {
2007   server_connection_id_ = server_connection_id;
2008 }
2009 
SetClientConnectionId(QuicConnectionId client_connection_id)2010 void QuicPacketCreator::SetClientConnectionId(
2011     QuicConnectionId client_connection_id) {
2012   QUICHE_DCHECK(client_connection_id.IsEmpty() ||
2013                 framer_->version().SupportsClientConnectionIds())
2014       << ENDPOINT;
2015   client_connection_id_ = client_connection_id;
2016 }
2017 
GetCurrentLargestMessagePayload() const2018 QuicPacketLength QuicPacketCreator::GetCurrentLargestMessagePayload() const {
2019   if (!VersionSupportsMessageFrames(framer_->transport_version())) {
2020     return 0;
2021   }
2022   const size_t packet_header_size = GetPacketHeaderSize(
2023       framer_->transport_version(), GetDestinationConnectionIdLength(),
2024       GetSourceConnectionIdLength(), IncludeVersionInHeader(),
2025       IncludeNonceInPublicHeader(), GetPacketNumberLength(),
2026       // No Retry token on packets containing application data.
2027       quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, GetLengthLength());
2028   // This is the largest possible message payload when the length field is
2029   // omitted.
2030   size_t max_plaintext_size =
2031       latched_hard_max_packet_length_ == 0
2032           ? max_plaintext_size_
2033           : framer_->GetMaxPlaintextSize(latched_hard_max_packet_length_);
2034   size_t largest_frame =
2035       max_plaintext_size - std::min(max_plaintext_size, packet_header_size);
2036   if (static_cast<QuicByteCount>(largest_frame) > max_datagram_frame_size_) {
2037     largest_frame = static_cast<size_t>(max_datagram_frame_size_);
2038   }
2039   return largest_frame - std::min(largest_frame, kQuicFrameTypeSize);
2040 }
2041 
GetGuaranteedLargestMessagePayload() const2042 QuicPacketLength QuicPacketCreator::GetGuaranteedLargestMessagePayload() const {
2043   if (!VersionSupportsMessageFrames(framer_->transport_version())) {
2044     return 0;
2045   }
2046   // QUIC Crypto server packets may include a diversification nonce.
2047   const bool may_include_nonce =
2048       framer_->version().handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
2049       framer_->perspective() == Perspective::IS_SERVER;
2050   // IETF QUIC long headers include a length on client 0RTT packets.
2051   quiche::QuicheVariableLengthIntegerLength length_length =
2052       quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0;
2053   if (framer_->perspective() == Perspective::IS_CLIENT) {
2054     length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
2055   }
2056   if (!QuicVersionHasLongHeaderLengths(framer_->transport_version())) {
2057     length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0;
2058   }
2059   const size_t packet_header_size = GetPacketHeaderSize(
2060       framer_->transport_version(), GetDestinationConnectionIdLength(),
2061       // Assume CID lengths don't change, but version may be present.
2062       GetSourceConnectionIdLength(), kIncludeVersion, may_include_nonce,
2063       PACKET_4BYTE_PACKET_NUMBER,
2064       // No Retry token on packets containing application data.
2065       quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, length_length);
2066   // This is the largest possible message payload when the length field is
2067   // omitted.
2068   size_t max_plaintext_size =
2069       latched_hard_max_packet_length_ == 0
2070           ? max_plaintext_size_
2071           : framer_->GetMaxPlaintextSize(latched_hard_max_packet_length_);
2072   size_t largest_frame =
2073       max_plaintext_size - std::min(max_plaintext_size, packet_header_size);
2074   if (static_cast<QuicByteCount>(largest_frame) > max_datagram_frame_size_) {
2075     largest_frame = static_cast<size_t>(max_datagram_frame_size_);
2076   }
2077   const QuicPacketLength largest_payload =
2078       largest_frame - std::min(largest_frame, kQuicFrameTypeSize);
2079   // This must always be less than or equal to GetCurrentLargestMessagePayload.
2080   QUICHE_DCHECK_LE(largest_payload, GetCurrentLargestMessagePayload())
2081       << ENDPOINT;
2082   return largest_payload;
2083 }
2084 
AttemptingToSendUnencryptedStreamData()2085 bool QuicPacketCreator::AttemptingToSendUnencryptedStreamData() {
2086   if (packet_.encryption_level == ENCRYPTION_ZERO_RTT ||
2087       packet_.encryption_level == ENCRYPTION_FORWARD_SECURE) {
2088     return false;
2089   }
2090   const std::string error_details =
2091       absl::StrCat("Cannot send stream data with level: ",
2092                    EncryptionLevelToString(packet_.encryption_level));
2093   QUIC_BUG(quic_bug_10752_37) << ENDPOINT << error_details;
2094   delegate_->OnUnrecoverableError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA,
2095                                   error_details);
2096   return true;
2097 }
2098 
HasIetfLongHeader() const2099 bool QuicPacketCreator::HasIetfLongHeader() const {
2100   return version().HasIetfInvariantHeader() &&
2101          packet_.encryption_level < ENCRYPTION_FORWARD_SECURE;
2102 }
2103 
2104 // static
MinPlaintextPacketSize(const ParsedQuicVersion & version,QuicPacketNumberLength packet_number_length)2105 size_t QuicPacketCreator::MinPlaintextPacketSize(
2106     const ParsedQuicVersion& version,
2107     QuicPacketNumberLength packet_number_length) {
2108   if (!version.HasHeaderProtection()) {
2109     return 0;
2110   }
2111   // Header protection samples 16 bytes of ciphertext starting 4 bytes after the
2112   // packet number. In IETF QUIC, all AEAD algorithms have a 16-byte auth tag
2113   // (i.e. the ciphertext is 16 bytes larger than the plaintext). Since packet
2114   // numbers could be as small as 1 byte, but the sample starts 4 bytes after
2115   // the packet number, at least 3 bytes of plaintext are needed to make sure
2116   // that there is enough ciphertext to sample.
2117   //
2118   // Google QUIC crypto uses different AEAD algorithms - in particular the auth
2119   // tags are only 12 bytes instead of 16 bytes. Since the auth tag is 4 bytes
2120   // shorter, 4 more bytes of plaintext are needed to guarantee there is enough
2121   // ciphertext to sample.
2122   //
2123   // This method could check for PROTOCOL_TLS1_3 vs PROTOCOL_QUIC_CRYPTO and
2124   // return 3 when TLS 1.3 is in use (the use of IETF vs Google QUIC crypters is
2125   // determined based on the handshake protocol used). However, even when TLS
2126   // 1.3 is used, unittests still use NullEncrypter/NullDecrypter (and other
2127   // test crypters) which also only use 12 byte tags.
2128   //
2129   return (version.UsesTls() ? 4 : 8) - packet_number_length;
2130 }
2131 
NextSendingPacketNumber() const2132 QuicPacketNumber QuicPacketCreator::NextSendingPacketNumber() const {
2133   if (!packet_number().IsInitialized()) {
2134     return framer_->first_sending_packet_number();
2135   }
2136   return packet_number() + 1;
2137 }
2138 
PacketFlusherAttached() const2139 bool QuicPacketCreator::PacketFlusherAttached() const {
2140   return flusher_attached_;
2141 }
2142 
HasSoftMaxPacketLength() const2143 bool QuicPacketCreator::HasSoftMaxPacketLength() const {
2144   return latched_hard_max_packet_length_ != 0;
2145 }
2146 
SetDefaultPeerAddress(QuicSocketAddress address)2147 void QuicPacketCreator::SetDefaultPeerAddress(QuicSocketAddress address) {
2148   if (!packet_.peer_address.IsInitialized()) {
2149     packet_.peer_address = address;
2150     return;
2151   }
2152   if (packet_.peer_address != address) {
2153     FlushCurrentPacket();
2154     packet_.peer_address = address;
2155   }
2156 }
2157 
2158 #define ENDPOINT2                                                          \
2159   (creator_->framer_->perspective() == Perspective::IS_SERVER ? "Server: " \
2160                                                               : "Client: ")
2161 
ScopedPeerAddressContext(QuicPacketCreator * creator,QuicSocketAddress address,bool update_connection_id)2162 QuicPacketCreator::ScopedPeerAddressContext::ScopedPeerAddressContext(
2163     QuicPacketCreator* creator, QuicSocketAddress address,
2164     bool update_connection_id)
2165     : ScopedPeerAddressContext(creator, address, EmptyQuicConnectionId(),
2166                                EmptyQuicConnectionId(), update_connection_id) {}
2167 
ScopedPeerAddressContext(QuicPacketCreator * creator,QuicSocketAddress address,const QuicConnectionId & client_connection_id,const QuicConnectionId & server_connection_id,bool update_connection_id)2168 QuicPacketCreator::ScopedPeerAddressContext::ScopedPeerAddressContext(
2169     QuicPacketCreator* creator, QuicSocketAddress address,
2170     const QuicConnectionId& client_connection_id,
2171     const QuicConnectionId& server_connection_id, bool update_connection_id)
2172     : creator_(creator),
2173       old_peer_address_(creator_->packet_.peer_address),
2174       old_client_connection_id_(creator_->GetClientConnectionId()),
2175       old_server_connection_id_(creator_->GetServerConnectionId()),
2176       update_connection_id_(update_connection_id) {
2177   QUIC_BUG_IF(quic_bug_12398_19, !old_peer_address_.IsInitialized())
2178       << ENDPOINT2
2179       << "Context is used before serialized packet's peer address is "
2180          "initialized.";
2181   creator_->SetDefaultPeerAddress(address);
2182   if (update_connection_id_) {
2183     // Flush current packet if connection ID length changes.
2184     if (address == old_peer_address_ &&
2185         ((client_connection_id.length() !=
2186           old_client_connection_id_.length()) ||
2187          (server_connection_id.length() !=
2188           old_server_connection_id_.length()))) {
2189       creator_->FlushCurrentPacket();
2190     }
2191     creator_->SetClientConnectionId(client_connection_id);
2192     creator_->SetServerConnectionId(server_connection_id);
2193   }
2194 }
2195 
~ScopedPeerAddressContext()2196 QuicPacketCreator::ScopedPeerAddressContext::~ScopedPeerAddressContext() {
2197   creator_->SetDefaultPeerAddress(old_peer_address_);
2198   if (update_connection_id_) {
2199     creator_->SetClientConnectionId(old_client_connection_id_);
2200     creator_->SetServerConnectionId(old_server_connection_id_);
2201   }
2202 }
2203 
2204 QuicPacketCreator::ScopedSerializationFailureHandler::
ScopedSerializationFailureHandler(QuicPacketCreator * creator)2205     ScopedSerializationFailureHandler(QuicPacketCreator* creator)
2206     : creator_(creator) {}
2207 
2208 QuicPacketCreator::ScopedSerializationFailureHandler::
~ScopedSerializationFailureHandler()2209     ~ScopedSerializationFailureHandler() {
2210   if (creator_ == nullptr) {
2211     return;
2212   }
2213   // Always clear queued_frames_.
2214   creator_->queued_frames_.clear();
2215 
2216   if (creator_->packet_.encrypted_buffer == nullptr) {
2217     const std::string error_details = "Failed to SerializePacket.";
2218     QUIC_BUG(quic_bug_10752_38) << ENDPOINT2 << error_details;
2219     creator_->delegate_->OnUnrecoverableError(QUIC_FAILED_TO_SERIALIZE_PACKET,
2220                                               error_details);
2221   }
2222 }
2223 
2224 #undef ENDPOINT2
2225 
set_encryption_level(EncryptionLevel level)2226 void QuicPacketCreator::set_encryption_level(EncryptionLevel level) {
2227   QUICHE_DCHECK(level == packet_.encryption_level || !HasPendingFrames())
2228       << ENDPOINT << "Cannot update encryption level from "
2229       << packet_.encryption_level << " to " << level
2230       << " when we already have pending frames: "
2231       << QuicFramesToString(queued_frames_);
2232   packet_.encryption_level = level;
2233 }
2234 
AddPathChallengeFrame(const QuicPathFrameBuffer & payload)2235 void QuicPacketCreator::AddPathChallengeFrame(
2236     const QuicPathFrameBuffer& payload) {
2237   // TODO(danzh) Unify similar checks at several entry points into one in
2238   // AddFrame(). Sort out test helper functions and peer class that don't
2239   // enforce this check.
2240   QUIC_BUG_IF(quic_bug_10752_39, !flusher_attached_)
2241       << ENDPOINT
2242       << "Packet flusher is not attached when "
2243          "generator tries to write stream data.";
2244   // Write a PATH_CHALLENGE frame, which has a random 8-byte payload.
2245   QuicFrame frame(QuicPathChallengeFrame(0, payload));
2246   if (AddPaddedFrameWithRetry(frame)) {
2247     return;
2248   }
2249   // Fail silently if the probing packet cannot be written, path validation
2250   // initiator will retry sending automatically.
2251   // TODO(danzh) This will consume retry budget, if it causes performance
2252   // regression, consider to notify the caller about the sending failure and let
2253   // the caller to decide if it worth retrying.
2254   QUIC_DVLOG(1) << ENDPOINT << "Can't send PATH_CHALLENGE now";
2255 }
2256 
AddPathResponseFrame(const QuicPathFrameBuffer & data_buffer)2257 bool QuicPacketCreator::AddPathResponseFrame(
2258     const QuicPathFrameBuffer& data_buffer) {
2259   QuicFrame frame(QuicPathResponseFrame(kInvalidControlFrameId, data_buffer));
2260   if (AddPaddedFrameWithRetry(frame)) {
2261     return true;
2262   }
2263 
2264   QUIC_DVLOG(1) << ENDPOINT << "Can't send PATH_RESPONSE now";
2265   return false;
2266 }
2267 
AddPaddedFrameWithRetry(const QuicFrame & frame)2268 bool QuicPacketCreator::AddPaddedFrameWithRetry(const QuicFrame& frame) {
2269   if (HasPendingFrames()) {
2270     if (AddPaddedSavedFrame(frame, NOT_RETRANSMISSION)) {
2271       // Frame is queued.
2272       return true;
2273     }
2274   }
2275   // Frame was not queued but queued frames were flushed.
2276   QUICHE_DCHECK(!HasPendingFrames()) << ENDPOINT;
2277   if (!delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
2278                                        NOT_HANDSHAKE)) {
2279     return false;
2280   }
2281   bool success = AddPaddedSavedFrame(frame, NOT_RETRANSMISSION);
2282   QUIC_BUG_IF(quic_bug_12398_20, !success) << ENDPOINT;
2283   return true;
2284 }
2285 
HasRetryToken() const2286 bool QuicPacketCreator::HasRetryToken() const { return !retry_token_.empty(); }
2287 
2288 #undef ENDPOINT  // undef for jumbo builds
2289 }  // namespace quic
2290